My 32ms C++ solution, clean and simple


  • 1
    H
    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            if(!head)
                return NULL;
            while(head!=NULL&&head->val==val)
            {
                ListNode* pt=head;
                head=head->next;
                delete pt;
            }
            if(!head)
                return NULL;
            ListNode* pPre=head;
            ListNode* pCur=head->next;
            while(pCur!=NULL)
            {
                if(pCur->val==val)
                {
                    ListNode* pt=pCur;
                    pPre->next=pCur->next;
                    delete pt;
                    pCur=pPre->next;
                }
                else
                {
                    pPre=pPre->next;
                    pCur=pCur->next;
                }
            }
            return head;
        }
    };

Log in to reply
 

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