/**
* 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 NULL;
map<RandomListNode*, RandomListNode*> m;//用map来存储神拷贝过的点
RandomListNode *ans = new RandomListNode(-1);//头节点
RandomListNode *node = head;
RandomListNode *pre = ans;
//方法不可行 是因为random不一定能够全部便利到
/*
ans->next = copyRandomList(head->next);
ans->random = copyRandomList(head->random);
*/
while(node!=NULL)
{
RandomListNode *temp = new RandomListNode(node->label);
//shared_ptr<RandomListNode> temp = make_shared<RandomListNode>(node->label);
m[node] = temp;//智能指针转化普通指针
pre->next = temp;
pre = temp;
node = node->next;
}
node = head;
RandomListNode *temp = ans->next;
while (node!=NULL)
{
temp->random = m[node->random];
temp = temp->next;
node = node->next;
}
return ans->next;
}
};
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.