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.
/**
* 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 == nullptr)
return nullptr;
RandomListNode *result = nullptr;
RandomListNode *pOld = head, *pNew = result;
do
{
pNew = new RandomListNode(pOld->label);
if(result == nullptr)
result = pNew;
pNew->next = pOld->next;
pOld->next = pNew;
pOld = pNew->next;
}while(pNew->next);
pOld = head;
while(pOld)
{
if(pOld->random)
pOld->next->random = pOld->random->next;
pOld = pOld->next->next;
}
pOld = head;
pNew = result;
while(pNew->next)
{
pOld->next = pNew->next;
pOld = pOld->next;
pNew->next = pOld->next;
pNew = pNew->next;
}
pOld->next = nullptr;
pNew->next = nullptr;
return result;
}
};