203. Remove Linked List Elements*
https://leetcode.com/problems/remove-linked-list-elements/
题目描述
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
C++ 实现 1
虚拟节点的使用. 如果遇到不等于 val
的节点, 就加入到 dummy 中.
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *dummy = new ListNode(0);
auto p = dummy;
while (head) {
if (head->val != val) {
p->next = head;
p = p->next;
}
head = head->next;
}
p->next = nullptr;
return dummy->next;
}
};