My C++ solution with a dummy pointer


  • 0
    L
    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            ListNode dummy(val-1);
            dummy.next = NULL;
            ListNode *cur = &dummy;
            cur->next = head;
            while(cur->next){
                if (cur->next->val != val)
                    cur = cur->next;
                else{
                    if (cur->next->next)
                        cur->next = cur->next->next;
                    else
                        cur->next = NULL;
                }
            }
            return dummy.next;
        }
    };

Log in to reply
 

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