Created
April 3, 2021 15:37
-
-
Save nomyfan/f10b3b22d274843d574d643b96df9c05 to your computer and use it in GitHub Desktop.
Reverse singly linkedlist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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