0%

[Leetcode]203. Remove Linked List Elements(C++)

题目描述

题目链接:203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

例子

例子 1

Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

解题思路

一次遍历,遇到下一个节点值为目标值时重新指向该节点的下一个节点并进行检查即可。

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
/**
* 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) {
ListNode* dummy = new ListNode();
dummy->next = head;
ListNode *curr = dummy;
while (curr && curr->next) {
while (curr->next && curr->next->val == val) {
curr->next = curr->next->next;
}
curr = curr->next;
}
return dummy->next;
}
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

GitHub 代码同步地址: 203.RemoveLinkedListElements.cpp

其他题目:
GitHub: Leetcode-C++-Solution
博客: Leetcode-Solutions