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]
说明:版权所有,转载请注明出处。 Coder007的博客/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// null node
if(NULL == head) return head;
// create new nodes of the old list
map<RandomListNode *, int> myMap; // stores the index of the nodes in the old list
vector<RandomListNode *> newNodes; // new nodes
RandomListNode *p = head;
int i = 0, j = 0;
while(p != NULL){
RandomListNode *node = new RandomListNode(p->label);
newNodes.push_back(node);
// stores index and increase index
myMap[p] = i++;
p = p->next;
}
// copy
p = head;
i = 0;
while(p != NULL){
if(p->next != NULL){
newNodes[i]->next = newNodes[i+1];
}
if(p->random != NULL){
newNodes[i]->random = newNodes[myMap[p->random]];
}
i++;
p = p->next;
}
return newNodes[0];
}
};