题目:
![](https://i-blog.csdnimg.cn/blog_migrate/8fc3fc701f41a94c064a27dc99910b46.png)
代码(首刷看解析 2024年1月11日):
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head==nullptr) return nullptr;
ListNode* BeforeHead = new ListNode(0,head);
ListNode* temp = BeforeHead;
while(temp->next != nullptr){
if(temp->next->val == val){
temp->next = temp->next->next;
}else{
temp = temp->next;
}
}
return BeforeHead->next;
}
};
代码(二刷自解 2024年4月15日 4min)
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummmyHead = new ListNode(0, head);
// 找到node = val的上一个,remove
ListNode* cur = dummmyHead;
while (cur && cur->next) {
while (cur && cur->next && cur->next->val == val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}
cur = cur->next;
}
return dummmyHead->next;
}
};