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) {
RandomListNode *pCurNode = head;
RandomListNode *pNewHead = NULL;
RandomListNode *pNewNode = NULL;
if (!head)
return NULL;
while (pCurNode)
{
RandomListNode *tmpNode = new RandomListNode(pCurNode->label);
tmpNode->next = pCurNode->next;
pCurNode->next = tmpNode;
/*
* wrong here, because the pCurNode->random may point to other node,
* so pCurNode->random->next may not point to the correct newCopy node
*/
/*
if (pCurNode->random)
{
tmpNode->random = pCurNode->random->next;
}
*/
pCurNode = pCurNode->next->next;
}
pCurNode = head;
while (pCurNode)
{
if (pCurNode->random)
{
pCurNode->next->random = pCurNode->random->next;
}
pCurNode = pCurNode->next->next;
}
pCurNode = head;
pNewHead = head->next;
pNewNode = pNewHead;
while (pCurNode)
{
pCurNode->next = pCurNode->next->next;
if (pNewNode->next)
{
pNewNode->next = pNewNode->next->next;
}
pCurNode = pCurNode->next;
pNewNode = pNewNode->next;
}
return pNewHead;
}
};