Copy List with Random Pointer

Easy Way but modify original List next 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) {
        RandomListNode dummy(-1);
        dummy.next = nullptr;
        dummy.random = nullptr;
        RandomListNode *tail = &dummy;
        vector<RandomListNode*> bk;

        int n = 0;
        for (RandomListNode *cur = head; cur != nullptr; ) {
            RandomListNode *node = new RandomListNode(cur->label);

            node->random = cur;

            tail->next = node;
            tail = tail->next;

            RandomListNode *tmp = cur->next;
            bk.push_back(cur->next);
            n++;
            cur->next = node;
            cur = tmp;
        }

        for (RandomListNode *cur = dummy.next; cur != nullptr; cur = cur->next) {
            cur->random = cur->random->random != nullptr ? cur->random->random->next : nullptr;

        }

        // restore the original list
        RandomListNode *cur = head;
        for (int i = 0; i < n; ++i) {
            cur->next = bk[i];
            cur = cur->next;
        }

        return dummy.next;   
    }
};

results matching ""

    No results matching ""