C++ solution 29 ms


  • 1
    P
    
     ListNode* removeElements(ListNode* head, int val) {
            if(head == NULL) return head;
            
            struct ListNode* current = head, *prev;
            
            while(current->next!= NULL){
                if(current->val==val) {
                     current->val = current->next->val;
                     current->next = current->next->next;
                }
                else{
                    prev = current;
                    current = current->next;
                }
            }
            if (current->val == val) prev->next = NULL;
            
            if(head->val == val) head = NULL; 
            return head;
            
        }
    

Log in to reply
 

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