leetcode/
delete_node.rs

1//! # 剑指 Offer 18. 删除链表的节点
2//!
3//! 难度 简单
4//!
5//! 给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
6//!
7//! 返回删除后的链表的头节点。
8//!
9//! 注意:此题对比原题有改动
10//!
11//! ## 示例 1:
12//!
13//! ```text
14//! 输入: head = [4,5,1,9], val = 5
15//! 输出: [4,1,9]
16//! 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
17//! ```
18//!
19//! ## 示例 2:
20//!
21//! ```text
22//! 输入: head = [4,5,1,9], val = 1
23//! 输出: [4,5,9]
24//! 解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
25//! ```
26//!
27//! ## 说明:
28//!
29//! * 题目保证链表中节点的值互不相同
30//! * 若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点
31//!
32//! See [leetcode](https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/)
33
34use crate::ListNode;
35
36pub struct Solution;
37
38impl Solution {
39
40    pub fn delete_node(head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
41        let mut dummy = Some(Box::new(ListNode{ next: head, val: 0 }));
42        let mut node = &mut dummy;
43        while node.is_some() && node.as_ref().unwrap().next.is_some() {
44            if node.as_ref().unwrap().next.as_ref().unwrap().val == val {
45                let n = node.as_mut().unwrap().next.take();
46                node.as_mut().unwrap().next = n.unwrap().next;
47                break;
48            }
49            node = &mut node.as_mut().unwrap().next;
50        }
51        dummy.unwrap().next
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58    use crate::list;
59
60    #[test]
61    fn test() {
62        let cases = vec![
63            (vec![4,1,9], (list![4,5,1,9], 5)),
64            (vec![4,5,9], (list![4,5,1,9], 1)),
65            (vec![], (list![], 1)),
66            (vec![4,1,9], (list![4,1,9], 3)),
67        ];
68
69        for (expect, (head, val)) in cases {
70            assert_eq!(expect, ListNode::into_vec(Solution::delete_node(head, val)));
71        }
72    }
73}