哈希
/*
// 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;
unordered_map<Node*, Node*> hashmap;
hashmap[NULL] = NULL;
for(auto p = head; p; p = p -> next)
hashmap[p] = new Node(p -> val);
for(auto p = head; p; p = p -> next)
{
hashmap[p] -> next = hashmap[p -> next];
hashmap[p] -> random = hashmap[p -> random];
}
return hashmap[head];
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head) return head;
//使用哈希来做一个映射
unordered_map<Node*, Node*> pos;
pos[NULL] = NULL;
//先复制正常的next节点,不复制random节点
for(auto p = head; p; p = p -> next)
pos[p] = new Node(p -> val);
//复制指针的指向
for(auto p = head; p; p = p -> next)
{
pos[p] -> next = pos[p -> next];
pos[p] -> random = pos[p -> random];
}
return pos[head];
}
};
/*
// Definition for a Node.
class Node {
p