12 ms iterative C solution for your reference, mad easy to understand


  • 1
    M
    struct ListNode* removeElements(struct ListNode* head, int val) {
        if (!head) return head;
    
        // Remove matching elements from start of list
        struct ListNode* newHead = head;
        while (newHead && newHead->val == val) newHead = newHead->next;
    
        // If list is now empty, we're done
        if (!newHead) return newHead;
    
        // Check to see if the next node needs to be removed. If so, we set the next of
        // the current node to the next next node. We need to be careful not to include
        // an increment instruction in the for loop, otherwise we risk skipping over a node 
        // without checking it first.
        for (struct ListNode *n = newHead; n->next;) {
            if (n->next->val == val) {
                n->next = n->next->next;
            } else {
                n = n->next;
            }
        }
    
        return newHead;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.