跳转至

203.Remove Linked List Elements

Tags: Easy Linked List

Links: https://leetcode.com/problems/remove-linked-list-elements/


Remove all elements from a linked list of integers that have value ***val***.

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

/**
 * 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) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        if (!head) return NULL;

        ListNode *dummy = new ListNode(INT_MIN);
        dummy -> next = head;
        ListNode *pre = dummy, *cur = head;

        while (cur) {
            if (cur -> val == val) {
                ListNode *tmp = cur;
                pre -> next = tmp -> next;
                cur = cur -> next;
                delete tmp; tmp = NULL;
            }
            else {
                cur = cur -> next;
                pre = pre -> next;
            }
        }

        ListNode *res = dummy -> next;
        delete dummy; dummy = NULL;

        return res;
    }
};