A 32ms C++ Solution


  • 2
    Y
     The comment part at last is another code that can pass all the test with one more variable.
     /**
     * 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 *newHead = head, *curr = head;
            while(curr) {
                if(newHead->val == val) {
                    curr = newHead->next;
                    newHead = newHead->next;
                    continue;
                }
                if(curr->next != NULL) 
                    if(curr->next->val == val) {
                        curr->next = curr->next->next;
                        continue;
                    }
                curr = curr->next;
            }
            return newHead;
    
            /*ListNode* listPtr = head, *pre = head, *newHead = head;
            while(listPtr != NULL) {
                if(newHead->val == val) {
                    pre = newHead->next;
                    listPtr = newHead->next;
                    newHead = newHead->next;
                    continue;
                }
                if(listPtr->val == val) pre->next = listPtr->next;
                else pre = listPtr;
                listPtr = listPtr->next;
            }
            return newHead;*/
        }
    };

Log in to reply
 

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