this is my C++ code ,use fakehead.


  • 0
    F

    class Solution {
    public:
    ListNode* removeElements(ListNode* head, int val) {
    ListNode* cur = head;
    ListNode* fakeHead = new ListNode(0);
    ListNode* pre = fakeHead;
    fakeHead->next = head;

        while(cur != NULL)
        {
            if(cur->val == val)
            {
               ListNode* p = cur;
               pre->next = cur->next;
               cur = cur->next;
               delete p;
            }
            else
            {
                pre = pre->next;
                cur = cur->next; 
            }
        }
        ListNode* p = fakeHead->next;
        delete fakeHead;
        return p;
    }
    

    };


Log in to reply
 

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