1,题目要求
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Example 1:
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.
Note:
You must return the copy of the given head as a reference to the cloned list.
给出链表,使得每个节点包含一个附加的随机指针,该指针可以指向列表中的任何节点或为空。
返回列表的深层副本。
2,题目思路
对于这道题,要求对一个含有随机指针的链表进行拷贝。
如果只是拷贝一个单纯的单链表,直接复制即可。但是题目给定的单链表有一个新的参数——random参数,这个指针会指向链表中的某一个节点。而且,复制的时候,是深拷贝,因此,需要利用开辟新新空间的方法来拷贝新的链表。
在问题的实现上,我们使用map来解决问题:
其中,key是原始链表中的节点,value是新链表中的节点。
如果mp[head]非空,则说明当前节点已经被拷贝了,直接返回这个节点即可。
如果为空,则对该节点进行创建——val、next和random。
3,代码实现
/*
// 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;
}
};
*/
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head)
return nullptr;
if(mp[head]!=nullptr)
return mp[head]; //拷贝链表已经有了这个节点
mp[head] = new Node(head->val);
mp[head]->next = copyRandomList(head->next);
mp[head]->random = copyRandomList(head->random);
return mp[head];
}
private:
unordered_map<Node*, Node*> mp;
};