// language C with STL(C++)
// 剑指35
// https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/comments/
// 同主站138
// https://leetcode-cn.com/problems/copy-list-with-random-pointer/
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
Node* CreatANode(int val){
Node* ans =(Node *) malloc(sizeof(Node));
ans->val = val;
ans->next = NULL;
ans->random = NULL;
return ans;
}
public:
Node* copyRandomList(Node* head) {
if(head == NULL)
return NULL;
// 先把链表的指针都装进一个vector里
vector<Node*> old;
Node* p = head;
while(p){
old.push_back(p);
p = p -> next;
}
int size_old = old.size();
int random[size_old];
for(int i = 0 ; i < size_old; i++){
p = old[i]->random;
if(p == NULL)
random[i] = -1;
else{
for(int j = 0; j<size_old; j++){
if(p == old[j])
random[i] = j;
}
}
}
Node* ans[size_old];
ans[size_old-1] = CreatANode(old[size_old-1]->val);
ans[size_old-1] ->next = NULL;
for(int i = size_old-2; i>=0; i--){
ans[i] = CreatANode(old[i]->val);
ans[i]->next = ans[i+1];
}
for(int i =0; i<size_old; i++){
if(random[i] != -1)
ans[i]->random = ans[random[i]];
}
return ans[0];
}
};