138. Copy List with Random Pointer

/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if (!head) return NULL;
        RandomListNode* curr = head;
        while (curr) {
            RandomListNode* tmp = curr->next;
            curr->next = new RandomListNode(curr->label);
            curr->next->next = tmp;
            curr = tmp;
        }

        curr = head;
        while (curr) {
            if (curr->random)
                curr->next->random = curr->random->next;
            curr = curr->next->next;
        } 

        RandomListNode* copyhead = head->next;
        RandomListNode* copycurr = head->next;
        curr = head;
        while (curr) {
            RandomListNode* tmp = curr->next->next;
            if (copycurr->next)
                copycurr->next = copycurr->next->next;
            curr->next = tmp;
            copycurr = copycurr->next;
            curr = curr->next;
        }
        return copyhead;
    }
};

results matching ""

    No results matching ""