Skip to content

Instantly share code, notes, and snippets.

@nomyfan
Created April 3, 2021 15:37
Show Gist options
  • Save nomyfan/f10b3b22d274843d574d643b96df9c05 to your computer and use it in GitHub Desktop.
Save nomyfan/f10b3b22d274843d574d643b96df9c05 to your computer and use it in GitHub Desktop.
Reverse singly linkedlist
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
fn reverse_until<'a>(
begin: Option<Box<ListNode>>,
end: Option<&'a Box<ListNode>>,
) -> Option<Box<ListNode>> {
let mut prev = None;
let mut cur = begin;
while cur.as_ref() != end {
let mut cur_unwrap = cur.unwrap();
let next = cur_unwrap.next.take();
cur_unwrap.next = prev.take();
prev = Some(cur_unwrap);
cur = next;
}
return prev;
}
fn reverse(begin: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
reverse_until(begin, None)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment