C++ 26ms solution


  • 0
    C
    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            if(!head)
                return head;
            ListNode *p = head;
            ListNode *pre = head;
            while(p->next){
               if(p->val == val){
                   p->val = p->next->val;
                   p->next= p->next->next;
               }else{
                   pre = p;
                   p = p->next;
               }
            }
            if(!p->next && p==head && p->val == val)
                head = NULL;
            else if(p!=head && p->val == val)
                pre->next = NULL;
            
            return head;
        }
    };
    

Log in to reply
 

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