My simple c++ solution beats 54 % users


  • -1
    A
    class Solution {    
    public:
        ListNode* removeElements(ListNode* head, int val) {
            if(!head) return head;
            while(head && head->val==val) head=head->next;
            ListNode * ans = head;
            while(head)
            {
                while(head->next && head->next->val == val) head->next = head->next->next;
                head=head->next;
            }
            return ans;
        }
    };

  • 2
    O

    You do not free any of deleted nodes, so there are a lot of memory leaks


  • 0

    class Solution {

    public:

    ListNode* removeElements(ListNode* head, int val) {

        if(!head) return head;    
        while(head && head->val==val) head=head->next;            
        ListNode * ans = head; 
        ListNode *anss;
        while(head)  
        {
            while(head->next && head->next->val == val) 
                 {   anss=head->next;
                     head->next = head->next->next;
                     delete anss;
                 }
            head=head->next;        
        }
        return ans;
    }
    

    };


Log in to reply
 

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