标题哈希表+遍历
先用哈希表创建并记录节点,再将指针捋顺了(新创建的节点指针指向空)
class Solution {
public:
Node* copyRandomList(Node* head) {
auto pre=head;
unordered_map<Node*,Node*>hashmap;
while(pre){
hashmap[pre]=new Node(pre->val);
pre=pre->next;
}
pre=head;
while(pre){
hashmap[pre]->next=hashmap[pre->next];
hashmap[pre]->random=hashmap[pre->random];
pre=pre->next;
}
return hashmap[head];
}
};