19. Remove Nth Node From End of List

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Follow up: Could you do this in one pass?

 

Example 1:

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

Input: head = [1], n = 1
Output: []

Example 3:

Input: head = [1,2], n = 1
Output: [1]

 

Constraints:

  • The number of nodes in the list is sz.
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

Rust Solution

struct Solution;
use rustgym_util::*;

impl Solution {
    fn remove_nth_from_end(mut head: ListLink, n: i32) -> ListLink {
        let mut v: Vec<ListLink> = vec![];
        while let Some(mut node) = head {
            head = node.next.take();
            v.push(Some(node));
        }
        let mut res = None;
        for (i, link) in v.into_iter().rev().enumerate() {
            if i != (n - 1) as usize {
                let mut node = link.unwrap();
                node.next = res;
                res = Some(node);
            }
        }
        res
    }
}

#[test]
fn test() {
    let head = list![1, 2, 3, 4, 5];
    let res = list![1, 2, 3, 5];
    let n = 2;
    assert_eq!(Solution::remove_nth_from_end(head, n), res);
}

Having problems with this solution? Click here to submit an issue on github.