My C++ Solution


  • 0
    Q
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            ListNode *dum = new ListNode(0);
            dum->next = head;
            ListNode *prev,*cur;
            prev = dum;
            cur = head;
            while(cur){
                while(cur && cur->val == val)
                    cur = cur->next;
                
                prev->next = cur;
    
                prev = cur;
                if(cur)                 //in case we delete tail nodes
                    cur = cur->next;
            }
            return dum->next;
        }
    };
    

Log in to reply
 

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