Solution Using fakeHead


  • 1
    C
    ListNode* removeElements(ListNode* head, int val) {
        ListNode fakeHead(0);
        ListNode* cur = &fakeHead;
        cur->next = head;
        while(cur->next){
            if(cur->next->val == val){
                cur->next = cur->next->next;
            }else if(cur->next)
                cur = cur->next;{
            }
        }
        return fakeHead.next;
    }

  • 0
    K

    I also create a fake head. Your code is more clean.


  • 0
    M

    You don't really need to check "cur->next" in the else if statement as it's already be checked in the while statement.


Log in to reply
 

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