问题描述:
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的深拷贝。
执行结果:
代码描述:
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head == NULL) return NULL;
Node* res = new Node(head->val, NULL, NULL);
Node* node = res;
Node* cur = head->next;
map<Node*, Node*> m;
m[head] = res;
while(cur)
{
Node *t = new Node(cur->val, NULL, NULL);
node->next = t;
m[cur] = t;
node = node->next;
cur = cur->next;
}
node = res;
cur = head;
while(cur)
{
node->random = m[cur->random];
node = node->next;
cur = cur->next;
}
return res;
}
};