forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#2625 from rmrt1n/019
Create 0019-remove-nth-node-from-end-of-list.rs
- Loading branch information
Showing
1 changed file
with
21 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
impl Solution { | ||
pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> { | ||
let mut dummy = Box::new(ListNode { val: 0, next: head.clone() }); | ||
let (mut left, mut right) = (dummy.as_mut(), head); | ||
|
||
let mut n = n; | ||
while n > 0 && right.is_some() { | ||
right = right.unwrap().next; | ||
n -= 1; | ||
} | ||
|
||
while let Some(r) = right { | ||
left = left.next.as_mut().unwrap(); | ||
right = r.next; | ||
} | ||
|
||
left.next = left.next.take().unwrap().next.take(); | ||
|
||
dummy.next | ||
} | ||
} |