复制带随机指针的链表

/*
// 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) {
//有技巧的
map<Node*, int> yingshe1;
map<int, Node*> yingshe2;
Node* node = head;
Node* newhead = new Node(1,NULL,NULL);
Node* node2 = newhead;
int count = 1;
while (node != NULL)//记录下来映射关系,同时把点构造出来
{
int temp = node->val;
auto tempnode = new Node(temp,NULL, NULL);
node2->next = tempnode;
yingshe1[node] = count;
yingshe2[count] = tempnode;
node = node->next;
node2 = node2->next;
++count;
}
node = head;
node2 = newhead->next;
while (node != NULL)
{
auto temp = node->random;
int index = yingshe1[temp];
auto randnode = yingshe2[index];
node2->random = randnode;
node = node->next;
node2 = node2->next;
}
return newhead->next;
}
};
