Skip to content

Instantly share code, notes, and snippets.

@swlkr
Created January 12, 2023 18:07
Show Gist options
  • Save swlkr/86fa6d609ad0cc07728a0494318cf6cd to your computer and use it in GitHub Desktop.
Save swlkr/86fa6d609ad0cc07728a0494318cf6cd to your computer and use it in GitHub Desktop.
Reverse a singly linked list in rust
#[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 push(&mut self, val: i32) {
if let Some(next) = &mut self.next {
next.push(val);
} else {
self.next = Some(Box::new(ListNode::new(val)));
}
}
fn head(&self) -> i32 {
self.val
}
}
struct Solution {}
pub fn reverse_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut list = head.clone();
let mut prev: Option<Box<ListNode>> = None;
while let Some(h) = &mut list {
let next = std::mem::replace(&mut h.next, prev.to_owned());
prev = list;
list = next;
}
return prev;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment