Skip to content

Commit 4a7fd4a

Browse files
authored
remove nth node from end of list solution
1 parent 74835d5 commit 4a7fd4a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Definition for singly-linked list.
2+
// #[derive(PartialEq, Eq, Clone, Debug)]
3+
// pub struct ListNode {
4+
// pub val: i32,
5+
// pub next: Option<Box<ListNode>>
6+
// }
7+
//
8+
// impl ListNode {
9+
// #[inline]
10+
// fn new(val: i32) -> Self {
11+
// ListNode {
12+
// next: None,
13+
// val
14+
// }
15+
// }
16+
// }
17+
impl Solution {
18+
pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
19+
let mut dummy = Some(Box::new(ListNode::new(0)));
20+
dummy.as_mut().unwrap().next = head;
21+
Self::solve(&mut dummy, n);
22+
dummy.unwrap().next
23+
}
24+
fn solve(head: &mut Option<Box<ListNode>>, n: i32) -> i32 {
25+
match head {
26+
None => 0,
27+
Some(u) => {
28+
let ans = Self::solve(&mut u.next, n) + 1;
29+
if ans == n + 1 {
30+
u.next = u.next.as_mut().unwrap().next.take();
31+
}
32+
ans
33+
}
34+
}
35+
}
36+
}

0 commit comments

Comments
 (0)