File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments