移除链表元素

移除链表元素

CategoryDifficultyLikesDislikes
algorithmsEasy (54.76%)1199-

Tags

linked-list

Companies

Unknown

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点

示例 1:

1
2
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]

示例 2:

1
2
输入:head = [], val = 1
输出:[]

示例 3:

1
2
输入:head = [7,7,7,7], val = 7
输出:[]

提示:

  • 列表中的节点数目在范围 [0, 104] 内
  • 1 <= Node.val <= 50
  • 0 <= val <= 50

Discussion | Solution

解法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// @lc code=start
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
//   pub val: i32,
//   pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
//   #[inline]
//   fn new(val: i32) -> Self {
//     ListNode {
//       next: None,
//       val
//     }
//   }
// }
impl Solution {
    /// ## 解题思路
    /// - 增加一个空的链表头指针;
    pub fn remove_elements1(head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
        let mut pre_head = Box::new(ListNode::new(0));
        pre_head.next = head;
        let mut p = &mut pre_head;
        while let Some(node) = p.next.take() {
            if node.val == val {
                p.next = node.next;
            } else {
                p.next = Some(node);
                p = p.next.as_mut().unwrap();
            }
        }

        pre_head.next
    }

    /// 递归
    pub fn remove_elements(head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
        match head {
            None => None,
            Some(mut head_node) => {
                let remaing = Self::remove_elements(head_node.next, val);
                if head_node.val == val {
                    remaing
                } else {
                    head_node.next = remaing;
                    Some(head_node)
                }
            }
        }
    }
}
// @lc code=end
updatedupdated2024-08-252024-08-25