From 699239f5bdf1edf8ce4427174d22762991c3a8d8 Mon Sep 17 00:00:00 2001 From: erius Date: Thu, 2 May 2024 13:49:02 +0300 Subject: [PATCH] Implemented p19 --- src/p19_remove_nth_node_from_end_of_list.rs | 26 +++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/p19_remove_nth_node_from_end_of_list.rs b/src/p19_remove_nth_node_from_end_of_list.rs index 6f713c4..8357307 100644 --- a/src/p19_remove_nth_node_from_end_of_list.rs +++ b/src/p19_remove_nth_node_from_end_of_list.rs @@ -1,9 +1,26 @@ use super::linked_list::ListNode; -struct Solution; +pub struct Solution; impl Solution { pub fn remove_nth_from_end(head: Option>, n: i32) -> Option> { - return None; + let mut head = head.unwrap(); + let mut node_before_nth: &mut Box; + // 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); }; + 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() { 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]); +}