C++ in O(n) run time 26ms Easy Solution


  • 0
    /**
     * 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* prev, *start;
            prev=NULL;
            start=head;
            
            while(head!=NULL)
            {
                if(head->val == val)
                {    
                    if(prev==NULL)
                    {
                        start=head;
                        head=head->next;
                        start->next=NULL;
                        delete start;
                        start=head;
                    }else
                    {
                        prev->next=head->next;
                        head->next=NULL;
                        delete head;
                        head=prev->next;
                    }
                    
                }else
                {
                    prev=head;
                    head=head->next;
                }
                
            }
            
            return start;
            
        }
    };
    

Log in to reply
 

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