Why am I getting the error that next pointer in original list was modified?


  • 0
    N
    class Solution {
    public:
        RandomListNode *copyRandomList(RandomListNode *head) {
            if (!head) {
                return NULL;
            }
            solve_helper1(head);
            solve_helper2(head);
            RandomListNode * copy_head = head->next;
            solve_helper3(head, copy_head);
            return copy_head;
        }
    
        void solve_helper1(RandomListNode *node) {
            if (!node) {
                return;
            }
            RandomListNode * copy = new RandomListNode(node->label);
            copy->next = node->next;
            node->next = copy;
            solve_helper1(copy->next);
        }
    
        void solve_helper2(RandomListNode *node) {
            if (node == NULL || node->next == NULL) {
                return;
            }
            if( node->random ) {
                node->next->random = node->random->next;
            }
            solve_helper2(node->next->next);
        }
    
        void solve_helper3(RandomListNode *node1, RandomListNode *node2) {
            if (node1 == NULL && node2 == NULL) {
                return;
            }
            if (node1->next) {
                node1->next = node2->next;
                node2->next = node1->next;
            }
            solve_helper3(node1->next, node2->next);
        }
    };
    

    Above is my code, I ran a few small test cases in my local machine and it worked fine, but when I submitted in LC it said the next pointer of the node with label 1 in original list was modified. Why is this? I checked my code a few times and didn't find the next pointer of original list was modified anywhere.


  • 0
    M

    I have the same question with you


Log in to reply
 

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