參考博客地址:Copy List with Random Pointer -- LeetCode
[LeetCode] Copy List with Random Pointer 拷貝帶有隨機指針的鏈表
題目地址:Copy List with Random Pointer
題目簡介:
給定一個鏈表,每個節點包含一個額外增加的隨機指針,該指針可以指向鏈表中的任何節點或空節點。要求返回這個鏈表的深拷貝。
示例:
Input:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}
Explanation:
Node 1's value is 1, both of its next and random pointer points to Node 2.
Node 2's value is 2, its next pointer points to null and its random pointer points to itself
題目解析:
在深拷貝面前,我就是個弟弟,解析參見開頭兩個博客。
C++代碼:
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node() {}
Node(int _val, Node* _next, Node* _random) {
val = _val;
next = _next;
random = _random;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
unordered_map<Node*, Node*> m;
return helper(head, m);
}
Node* helper(Node* node, unordered_map<Node*, Node*>& m) {
if (!node)
return nullptr;
if (m.count(node))
return m[node];
Node *res = new Node(node->val, nullptr, nullptr);
m[node] = res;
res->next = helper(node->next, m);
res->random = helper(node->random, m);
return res;
}
};