删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
题目标签:Linked List
题目链接:LeetCode / LeetCode中国
Language | Runtime | Memory |
---|---|---|
cpp | 24 ms | 1.7 MB |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* p = dummy;
while (p->next) {
if (p->next->val != val) {
p = p->next;
} else {
ListNode* t = p->next;
p->next = t->next;
delete t;
}
}
return dummy->next;
}
};
static auto _ = [](){ ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();