Copy List with Random Pointer
Easy Way but modify original List next pointer
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;
}
RandomListNode *cur = head;
for (int i = 0; i < n; ++i) {
cur->next = bk[i];
cur = cur->next;
}
return dummy.next;
}
};
