Implemented p19

This commit is contained in:
Egor 2024-05-02 13:49:02 +03:00
parent 71f8062bc5
commit 699239f5bd

View file

@ -1,9 +1,26 @@
use super::linked_list::ListNode; use super::linked_list::ListNode;
struct Solution; pub struct Solution;
impl Solution { impl Solution {
pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> { pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
return None; let mut head = head.unwrap();
let mut node_before_nth: &mut Box<ListNode>;
// unsafe is required to have immutable and mutable references at the same time
// in order to avoid cloning the list altogether
unsafe { node_before_nth = &mut *(&mut head as *mut Box<ListNode>); };
let mut tail = &head;
for _ in 0..n-1 {
tail = tail.next.as_ref().unwrap();
}
if tail.next.is_none() { return head.next; }
else { tail = tail.next.as_ref().unwrap(); }
while tail.next.is_some() {
tail = tail.next.as_ref().unwrap();
node_before_nth = node_before_nth.next.as_mut().unwrap();
}
let node_to_remove = node_before_nth.next.as_mut().unwrap();
node_before_nth.next = node_to_remove.next.take();
return Some(head);
} }
} }
@ -21,3 +38,8 @@ fn test2() {
fn test3() { fn test3() {
assert_eq!(Solution::remove_nth_from_end(list![1,2], 1), list![1]); assert_eq!(Solution::remove_nth_from_end(list![1,2], 1), list![1]);
} }
#[test]
fn test4() {
assert_eq!(Solution::remove_nth_from_end(list![1,2], 2), list![2]);
}