C++ Solution in about 30ms


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

Log in to reply
 

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