My soluttion with C++


  • 0
    M
    RandomListNode *copyRandomList(RandomListNode *head) {
        cloneNodes(head);
        connectRandomNodes(head);
        return reconnectNodes(head);
    }
    
    // Clone every node
    void cloneNodes(RandomListNode *head) {
        RandomListNode *pNode = head;
        while (NULL != pNode) {
            RandomListNode *pClone = new RandomListNode(pNode->label);
            pClone->next = pNode->next;
            pNode->next = pClone;
            pNode = pClone->next;
        }
    }
    
    // Set random of cloned nodes
    void connectRandomNodes(RandomListNode *head) {
        RandomListNode *pNode = head;
        while (NULL != pNode) {
            RandomListNode *pClone = pNode->next;
            if (NULL != pNode->random) {
                pClone->random = pNode->random->next;
            }
            pNode = pClone->next;
        }
    }
    
    // pcik up of the copy
    RandomListNode *reconnectNodes(RandomListNode *head) {
        RandomListNode *pNode = head;
        RandomListNode *pCloneHead = NULL;
        RandomListNode *pCloneNode = NULL;
        
        if (NULL != pNode) {
            pCloneHead = pCloneNode = pNode->next;
            pNode->next = pCloneNode->next;
            pNode = pNode->next;
        }
        
        while (NULL != pNode) {
            pCloneNode->next = pNode->next;
            pCloneNode = pCloneNode->next;
            pNode->next = pCloneNode->next;
            pNode = pNode->next;
        }
        
        return pCloneHead;
    }

Log in to reply
 

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