题目描述
增设虚拟头节点
仅用pre遍历
/**
* 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 == nullptr) return nullptr;
ListNode* dummyNode = new ListNode(0);
dummyNode->next = head;
ListNode* pre = dummyNode, *temp = nullptr;
while(pre->next != nullptr) {
if(pre->next->val == val) {
temp = pre->next;
pre->next = temp->next;
delete temp;
}else{
pre = pre->next;
}
}
head = dummyNode->next;
delete dummyNode;
return head;
}
};
用pre和cur遍历
/**
* 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 == nullptr) return nullptr;
ListNode* dummyNode = new ListNode(0);
dummyNode->next = head;
ListNode* pre = dummyNode, *cur = dummyNode->next, *temp = nullptr;
while(cur != nullptr) {
if(cur->val == val) {
temp = cur;
pre->next = temp->next;
cur = temp->next;
delete temp;
}else{
pre = pre->next;
cur = cur->next;
}
}
head = dummyNode->next;
delete dummyNode;
return head;
}
};
原题链接:203. 移除链表元素