AC simple C++ solution


  • 0
    L

    idea show in comments.

    ListNode* removeElements(ListNode* head, int val) {
     
        // remove any head node that vale is val 
        while (head != NULL)
        {
            if (head->val == val)
                head = head->next;
            else
                break;
        }
        if (head == NULL)
            return head;     
        
        // now the list contains at least one node, and the head node vale is not val 
        ListNode *p = head;
            
        while(p->next != NULL)
        {
            if (p->next->val == val)   
                p->next = p->next->next;
            else
                p = p->next;
        }
        
        return head;
    }

Log in to reply
 

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