C++ solution that cleans up deleted node


  • 0
    T

    Well, I think thought the description is not requiring us to clean up the memory of deleted nodes, it's still worth doing because C++ does not have an automated GC and programmer is responsible for memory cleanup.

    /**
     * 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* cur = head;
            ListNode* prev = nullptr;
            ListNode* newHead = head;
            
            while(cur){
                if(val == cur->val){
                    if(prev){
                        prev->next = cur->next;
                    }
                    else{ //head is removed
                        newHead = cur->next;
                    }
                    
                    ListNode* toDelete = cur;
                    cur = cur->next;
                    delete toDelete;
                }
                else{
                    prev = cur;
                    cur = cur->next;
                }
            }
            
            return newHead;
        }
    };
    

Log in to reply
 

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