/**
* 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 *p, *t;
while(head && head->val == val){ //单独处理头节点
t = head;
head = head->next;
delete t;
}
p = head;
while(head && head->next){
if(head->next->val == val){
t = head->next;
head->next = head->next->next;
delete t;
}else head = head->next;
}
head = p;
return head;
}
};
/**
* 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 *p = new ListNode(), *t; //使用辅助头节点
p->next = head;
head = p;
while(head->next){
if(head->next->val == val){
t = head->next;
head->next = head->next->next;
delete t;
}else head = head->next;
}
head = p->next;
delete p;
return head;
}
};