Easy to understand c++ code 32ms


  • 0
    Q
    ListNode* removeElements(ListNode* head, int val) {
        // skip the head element equals val
        while(head) {
            if(head->val==val)
                head = head->next;
            else break;
        }
        if(!head) return NULL;
        
        ListNode* headOri = head;
        ListNode* prev = head;  // keep the previous pointer
        
        while(head) {
            if(head->val==val) prev->next = head->next;  // remove current node
            else prev = head;  // update previous pointer
            head = head->next;
        }
        return headOri;
    }

Log in to reply
 

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