138. 复制带随机指针的链表
给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的 深拷贝。
我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:
val:一个表示 Node.val 的整数。
random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为 null 。
DFS+递归实现深拷贝
/*
// 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:
Node* copyRandomList(Node* head) {
if(!head) return head;
if(visited[head]) return visited[head];
Node * res=new Node(head->val);
visited[head]=res;
res->next=copyRandomList(head->next);
res->random=copyRandomList(head->random);
return res;
}
private:
unordered_map<Node*,Node*> visited;
};
BFS+队列实现深拷贝
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head) return head;
visited[head]=new Node(head->val);
queue<Node*> Q;
Q.push(head);
while(!Q.empty()){
Node* tmp=Q.front();
Q.pop();
if(tmp->next){
if(!visited[tmp->next]) {
visited[tmp->next]=new Node(tmp->next->val);
Q.push(tmp->next);
}
visited[tmp]->next=visited[tmp->next];
}
if(tmp->random){
if(!visited[tmp->random]){
visited[tmp->random]=new Node(tmp->random->val);
Q.push(tmp->random);
}
visited[tmp]->random=visited[tmp->random];
}
}
return visited[head];
}
private:
unordered_map<Node*,Node*> visited;
};