题目要求
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
题解
简单题的简单做法
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode dummy(-1);
dummy.next=head;
for(ListNode *pre=&dummy,*cur=head;cur;cur=cur->next){
if(cur->val==val){
pre->next=cur->next;
continue;
}
pre=pre->next;
}
return dummy.next;
}
};
官方严谨版
作者:LeetCode
链接:https://leetcode-cn.com/problems/remove-linked-list-elements/solution/yi-chu-lian-biao-yuan-su-by-leetcode/
同时把移出的节点给delete了。
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* sentinel = new ListNode(0);
sentinel->next = head;
ListNode *prev = sentinel, *curr = head, *toDelete = nullptr;
while (curr != nullptr) {
if (curr->val == val) {
prev->next = curr->next;
toDelete = curr;
} else prev = curr;
curr = curr->next;
if (toDelete != nullptr) {
delete toDelete;
toDelete = nullptr;
}
}
ListNode *ret = sentinel->next;
delete sentinel;
return ret;
}
};