C++ PreHead with Memory Delete


  • 0
    S

    Algorithm Steps

    • Create PreHead
    • Ensure cur->next always exists
    • If cur->next matches val, remove it; otherwise, go to next node
    • return preHead->next
        ListNode* removeElements(ListNode* head, int val) {
            ListNode* preHead = new ListNode(-1);
            preHead->next = head;
            for(ListNode *cur = preHead; cur->next; ) {
                if (cur->next->val == val) {
                    ListNode *deleteMe = cur->next;
                    cur->next = cur->next->next;
                    delete deleteMe;
                } else {
                    cur = cur->next;
                }
            }
            return preHead->next;
        }
    

Log in to reply
 

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