题目链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/
题目如下:
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
unordered_map<Node*,Node*> node_map;//map中记录每一个节点对应新节点的创建情况,key:原链表,value:copy后的链表节点
Node* copyRandomList(Node* head) {
//注:copy节点时,cur节点的random节点可能没创建。故用回溯,让每个节点的copy操作相互独立
if(head==NULL) return NULL;
if(node_map.count(head)==0){
Node* cur=new Node(head->val);
node_map[head]=cur;
cur->next=copyRandomList(head->next);
cur->random=copyRandomList(head->random);
}
return node_map[head];
}
};