|
| 1 | +/** |
| 2 | + * [19] 删除链表的倒数第 N 个结点 |
| 3 | + * |
| 4 | + * 给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。 |
| 5 | + * |
| 6 | + * 示例 1: |
| 7 | + * <img alt="" src="https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg" style="width: 542px; height: 222px;" /> |
| 8 | + * 输入:head = [1,2,3,4,5], n = 2 |
| 9 | + * 输出:[1,2,3,5] |
| 10 | + * |
| 11 | + * 示例 2: |
| 12 | + * |
| 13 | + * 输入:head = [1], n = 1 |
| 14 | + * 输出:[] |
| 15 | + * |
| 16 | + * 示例 3: |
| 17 | + * |
| 18 | + * 输入:head = [1,2], n = 1 |
| 19 | + * 输出:[1] |
| 20 | + * |
| 21 | + * |
| 22 | + * 提示: |
| 23 | + * |
| 24 | + * 链表中结点的数目为 sz |
| 25 | + * 1 <= sz <= 30 |
| 26 | + * 0 <= Node.val <= 100 |
| 27 | + * 1 <= n <= sz |
| 28 | + * |
| 29 | + * |
| 30 | + * 进阶:你能尝试使用一趟扫描实现吗? |
| 31 | + * |
| 32 | + */ |
| 33 | +pub struct Solution {} |
| 34 | +use std::borrow::BorrowMut; |
| 35 | + |
| 36 | +use crate::util::linked_list::{ListNode, to_list}; |
| 37 | + |
| 38 | +// problem: https://leetcode.cn/problems/remove-nth-node-from-end-of-list/ |
| 39 | +// discuss: https://leetcode.cn/problems/remove-nth-node-from-end-of-list/discuss/?currentPage=1&orderBy=most_votes&query= |
| 40 | + |
| 41 | +// submission codes start here |
| 42 | + |
| 43 | +// Definition for singly-linked list. |
| 44 | +// #[derive(PartialEq, Eq, Clone, Debug)] |
| 45 | +// pub struct ListNode { |
| 46 | +// pub val: i32, |
| 47 | +// pub next: Option<Box<ListNode>> |
| 48 | +// } |
| 49 | +// |
| 50 | +// impl ListNode { |
| 51 | +// #[inline] |
| 52 | +// fn new(val: i32) -> Self { |
| 53 | +// ListNode { |
| 54 | +// next: None, |
| 55 | +// val |
| 56 | +// } |
| 57 | +// } |
| 58 | +// } |
| 59 | +impl Solution { |
| 60 | + pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> { |
| 61 | + let mut dummy_head = Box::new(ListNode { |
| 62 | + next: head, |
| 63 | + val: 0, |
| 64 | + }); |
| 65 | + unsafe { |
| 66 | + let mut slow = &mut dummy_head as *mut Box<ListNode>; |
| 67 | + let mut fast = &mut dummy_head as *mut Box<ListNode>; |
| 68 | + for _ in 0..n { |
| 69 | + fast = (*fast).next.as_mut().unwrap(); |
| 70 | + } |
| 71 | + while (*fast).next.is_some() { |
| 72 | + fast = (*fast).next.as_mut().unwrap(); |
| 73 | + slow = (*slow).next.as_mut().unwrap(); |
| 74 | + } |
| 75 | + (*slow).next = (*slow).next.take().unwrap().next; |
| 76 | + } |
| 77 | + dummy_head.next |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +// submission codes end |
| 82 | + |
| 83 | +#[cfg(test)] |
| 84 | +mod tests { |
| 85 | + use super::*; |
| 86 | + |
| 87 | + #[test] |
| 88 | + fn test_19() { |
| 89 | + assert_eq!( |
| 90 | + Solution::remove_nth_from_end(to_list(vec![1, 2, 3, 4, 5]), 2), |
| 91 | + to_list(vec![1, 2, 3, 5]) |
| 92 | + ); |
| 93 | + assert_eq!(Solution::remove_nth_from_end(to_list(vec![1]), 1), None); |
| 94 | + } |
| 95 | +} |
0 commit comments