思路:
一、直接在原链表上操作:
1、如果第一个为目标元素,将头节点更新为下一个
2、如果不是第一个替换下一个元素为下下一个
注意:删除第一个元素要用while而不是if
原因:删完第一个,第二个也可能是目标val
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
//第一个节点是删除目标,删掉
while(head != NULL && head->val == val ){
ListNode *temp = head;
head = head->next;
delete temp;
}
//else;
ListNode *current = head;
while(current != NULL && current->next != NULL){
if(current->next->val == val){
ListNode *temp = current->next;
current->next = current->next->next;
delete temp;
}else{
current = current->next;
}
}
return head;
}
};
二、设置一个虚拟节点指向的下一个元素为head
注意:head在末尾要再执行一遍赋值操作,即将head的值变为虚拟头节点的下一个
原因:return直接返回head,当head的val值等于目标val时,此时的head可能已经被删除
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode *current = dummyhead;
while(current->next != NULL){
if(current->next->val == val){
ListNode *temp = current->next;
current->next = current->next->next;
delete temp;
}else{
current = current->next;
}
}
head = dummyhead->next;
delete dummyhead;
return head;
}
};