A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Solution:Code:
<span style="font-size:14px;">/**
* 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 == NULL) return head;
RandomListNode *copyHead = head, *copy;
while (copyHead != NULL) {
copy = new RandomListNode(copyHead->label);
copy->next = copyHead->next;
copyHead->next = copy;
copyHead = copy->next;
}
copyHead = head;
while (copyHead != NULL) {
if (copyHead->random)
copyHead->next->random = copyHead->random->next;
copyHead = copyHead->next->next;
}
copyHead = head->next;
copy = copyHead;
while (head != NULL) {
head->next = copy->next;
head = head->next;
if (head == NULL) break;
copy->next = head->next;
copy = copy->next;
}
return copyHead;
}
};</span>