Simple C++ Solution


  • 1
    J
    class Solution {
    public:
    ListNode* removeElements(ListNode* head, int val) {
        if(!head) return NULL;
        
        ListNode* newHead = new ListNode(INT_MIN);
        newHead->next = head;
        
        ListNode* cur = head;
        ListNode* prev = newHead;
        while(cur)
        {
            if(cur->val == val)
            {
                ListNode* t = cur;
                prev->next = cur->next;
                cur = cur->next;
                delete t;
                continue;
            }
            
            prev = cur;
            cur = cur->next;
        }
        
        ListNode* t = newHead->next;
        delete newHead;
        return t;
      }
    };

  • 0
    F
    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            ListNode *p = (ListNode *)malloc(sizeof(struct ListNode));// p's next is head (p is just a pointer)
            p->next = head;
            head = p;
            while(head){
                ListNode *np = head->next;// np try to point to the next proper ListNode (np is another pointer)
                while(np && np->val == val)
                    np = np->next;
                head->next = np;
                head = np;
            }
            return p->next;
        }
    };
    

    Note: I am lazy, so I skipped the process to return the free space. It is a bad habit...


  • 0
    Z

    Just create the newHead on stack to avoid your bad habit...


  • 0
    F

    Yeah, that is one way~


Log in to reply
 

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