C++ Iterative Solution


  • 0
    Y

    If the element to be removed is in the head, you need to update head.

    class Solution {
    public:
    ListNode* removeElements(ListNode* head, int val) {

        if (head == NULL) {
            return NULL;
        }
        if (head->next == NULL && head->val == val) {
            return NULL;
        }
        ListNode* prev=NULL;
        ListNode* curr=head;
        while (curr != NULL) {
            if (curr->val == val) {
                if (prev == NULL) {
                    head = curr->next;
                }
                else {
                    prev->next = curr->next; 
                } 
            }
            else {
                prev = curr;
            }
            curr = curr->next;
        }
        return head;
        
    }
    

    };


Log in to reply
 

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