程式語言 - LeetCode - C++ - 203. Remove Linked List Elements



題目:


解答:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode d0;
        d0.next = head;

        ListNode *pre = &d0;
        ListNode *cur = head;

        while (cur) {
            if (cur->val == val) {
                pre->next = cur->next;
            }
            else {
                pre = cur;
            }
            cur = cur->next;
        }

        return d0.next;
    }
};