
Copy List with Random Pointer
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.
算法分为三步:
1. copy and insert
2. set random pointer of copied node
3. split these two list
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(head == NULL) return NULL;
//1. copy and insert
RandomListNode* pCurNode = head;
while(pCurNode != NULL)
{
//copy
RandomListNode* tmp = new RandomListNode(pCurNode->label);
//insert
RandomListNode* pNextNode = pCurNode->next;
pCurNode->next = tmp;
tmp->next = pNextNode;
pCurNode = pNextNode;
}
//2. set random pointer of copied node
pCurNode = head;
while(pCurNode != NULL)
{
if(pCurNode->random != NULL)
pCurNode->next->random = pCurNode->random->next;
else
pCurNode->next->random = NULL;
pCurNode = pCurNode->next->next;
}
//3. split these two list
RandomListNode* newHead = head->next;
pCurNode = head;
while(pCurNode != NULL)
{
RandomListNode* pCopiedNode = pCurNode->next;
pCurNode->next = pCurNode->next->next;
if(pCurNode->next != NULL)
pCopiedNode->next = pCurNode->next->next;
else
pCopiedNode->next = NULL;
pCurNode = pCurNode->next;
}
return newHead;
}
};leetcode_138_ Copy List with Random Pointer
原文地址:http://blog.csdn.net/keyyuanxin/article/details/43850917