Skip to content

Instantly share code, notes, and snippets.

@time-river
Last active February 27, 2024 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save time-river/8095ad30089567da18d21cfe599af2bc to your computer and use it in GitHub Desktop.
Save time-river/8095ad30089567da18d21cfe599af2bc to your computer and use it in GitHub Desktop.
rust-reference
// bad
pub fn remove_linked_list_elements(head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
let mut dummy = Some(Box::new(ListNode{val: 0, next: None}));
let mut prev = dummy.as_mut();
let mut curr = head;
while let Some(mut node) = curr {
curr = node.next.take();
if node.val != val {
// bad here
prev.unwrap().next = Some(node);
// but it's good
// prev.as_mut().unwrap().next = Some(node);
prev = prev.unwrap().next.as_mut();
}
}
dummy?.next
}
// good
pub fn remove_linked_list_elements(head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
let mut dummy = Some(Box::new(ListNode{val: 0, next: None}));
let mut prev = dummy.as_mut();
let mut curr = head;
while let Some(mut node) = curr {
curr = node.next.take();
if node.val != val {
// good
let pnode = prev.unwrap();
pnode.next = Some(node);
prev = pnode.next.as_mut();
}
}
dummy?.next
}
// good
impl Solution {
pub fn remove_elements(mut head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
let mut dummy = Some(Box::new(ListNode::new(0)));
let mut next = dummy.as_mut();
while let Some(mut inner) = head {
head = inner.next.take();
if inner.val != val {
// good
next.as_mut().unwrap().next = Some(inner);
next = next.unwrap().next.as_mut();
}
}
dummy.unwrap().next
}
}
// good
pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
let mut length = 0;
{
let mut p = head.as_ref();
while let Some(node) = p {
length += 1;
p = node.next.as_ref();
}
}
let mut dummy = Some(Box::new(ListNode{val: 0, next: head}));
let mut p = dummy.as_mut();
for _ in 0..(length-n) {
p = p.unwrap().next.as_mut();
}
// good
let curr = p.unwrap();
let del = curr.next.as_mut()?;
curr.next = del.next.take();
return dummy.unwrap().next;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment