203 移除链表元素

本文最后更新于:2022年8月27日 晚上

删除链表中等于给定值 val 的所有节点。

示例:

1
2
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

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
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(!head) return head;
ListNode* dummyHead = new ListNode(-1, head);
ListNode* cur = dummyHead;
while(cur->next){
if(cur->next->val==val){
ListNode* delNode = cur->next;
cur->next = delNode->next;
delete delNode;
}else{
cur = cur->next;
}
}
return dummyHead->next;
}
};
// @lc code=end
  • 递归法
1
2
3
4
5
6
7
8
9
10
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head==nullptr){
return head;
}
head->next = removeElements(head->next, val);
return head->val == val ? head->next : head;
}
};

java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
ListNode dummyHead = new ListNode(-1, head);
ListNode cur = dummyHead;
while (cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return dummyHead.next;
}
}

迭代法

1
2
3
4
5
6
7
8
9
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!