C++: Are we NOT supposed to free list node?

  • 1

    The following code will work if we don't free the list node. If we do free the list node, then runtime error will pop out.

    class Solution {
        TreeNode* sortedListToBST(ListNode* head) {
            if (head==NULL){
                return NULL;
            ListNode *newhead = new ListNode(0);
            newhead->next = head;
            ListNode *slow=newhead, *fast=newhead;
            while(fast->next && fast->next->next){
                fast = fast->next->next;
                slow = slow->next;
            // slow->next is the root
            TreeNode *root = new TreeNode(slow->next->val);
            ListNode *tmp = slow->next->next;
            root->right = sortedListToBST(tmp);
            //delete slow->next; XXX not sure why this will make Runtime Error
            slow->next = NULL;
            tmp = newhead->next;
            delete newhead;
            root->left = sortedListToBST(tmp);
            return root;

  • 0

    I encountered the same problem in my C solution. After commenting free statement, it seemed to work. Maybe a bug in the calling test program ?

  • 1

    I do have the same question. I guess Leetcode OJ has its own memory collection scheme. OJ will delete any allocated memory to avoid memory leak. So if you delete in your own function, a double delete might happen when OJ tries to delete.

Log in to reply

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