//Hashmap, copy node; then copy random;
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
unordered_map<RandomListNode*, RandomListNode*> old2new;
RandomListNode* dummy = new RandomListNode(-1);
RandomListNode* tmp = head;
RandomListNode* curr = dummy;
while (tmp) {
RandomListNode* newNode = new RandomListNode(tmp->label);
old2new[tmp] = newNode;
curr->next = newNode;
curr = curr -> next;
tmp = tmp->next;
}
tmp = head;
while (tmp) {
//if (tmp->random) {
old2new[tmp]->random = old2new[tmp->random];
//}
tmp = tmp-> next;
}
return dummy->next;
}
};
public class Solution {
private void copyNext(RandomListNode head) {
while (head != null) {
RandomListNode newNode = new RandomListNode(head.label);
newNode.random = head.random;
newNode.next = head.next;
head.next = newNode;
head = head.next.next;
}
}
private void copyRandom(RandomListNode head) {
while (head != null) {
if (head.next.random != null) {
head.next.random = head.random.next;
}
head = head.next.next;
}
}
private RandomListNode splitList(RandomListNode head) {
RandomListNode newHead = head.next;
while (head != null) {
RandomListNode temp = head.next;
head.next = temp.next;
head = head.next;
if (temp.next != null) {
temp.next = temp.next.next;
}
}
return newHead;
}
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
return null;
}
copyNext(head);
copyRandom(head);
return splitList(head);
}
}
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL) {
return NULL;
}
duplicateNodes(head);
copyRandomNodes(head);
return splitLists(head);
}
void duplicateNodes(RandomListNode *head) {
RandomListNode* cur = head;
while (cur != NULL) {
cur = copyNodes(cur);
}
return;
}
RandomListNode* copyNodes(RandomListNode* cur) {
RandomListNode* next = cur->next;
RandomListNode* newNode = new RandomListNode(cur->label);
cur->next = newNode;
newNode->next = next;
return next;
}
void copyRandomNodes(RandomListNode *head) {
RandomListNode *cur = head;
while (cur != NULL) {
cur = setRandomNodes(cur);
}
return;
}
RandomListNode* setRandomNodes(RandomListNode* cur) {
if (cur->random == NULL) {
return cur->next->next;
}
RandomListNode* dupRandomNode = cur->random->next;
cur->next->random = dupRandomNode;
return cur->next->next;
}
RandomListNode* splitLists(RandomListNode* head) {
RandomListNode* dummyOld = new RandomListNode(0);
RandomListNode* dummyNew = new RandomListNode(0);
dummyOld->next = dummyNew;
dummyNew->next = head;
RandomListNode* cur = dummyOld;
while (cur != NULL) {
cur = splitOnePair(cur);
}
return dummyNew->next;
}
RandomListNode* splitOnePair(RandomListNode* cur) {
RandomListNode* next = cur->next->next;
RandomListNode* newNode = cur->next;
cur->next = next;
if (next != NULL) {
newNode->next = next->next;
}
return next;
}
};