Skip to content

Latest commit

 

History

History
57 lines (43 loc) · 1.44 KB

203-remove-linked-list-elements.md

File metadata and controls

57 lines (43 loc) · 1.44 KB

203. Remove Linked List Elements - 移除链表元素

删除链表中等于给定值 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; }();