Node* copyRandomList(Node* head) {
if(!head) return NULL;
for(auto p=head;p;p=p->next){
hash[p]=new Node(p->val);
}
for(auto p=head;p;p=p->next){
hash[p]->next=hash[p->next];
hash[p]->random=hash[p->random];
}
return hash[head];
}
当然,此处贴上y总的空间开销更小的算法
Node* copyRandomList(Node* head) {
for(auto p=head;p;p=p->next->next){//复制第一个小弟
auto q=new Node(p->val);
q->next=p->next;
p->next=q;
}
for(auto p=head;p;p=p->next->next){//复制random
if(p->random)
p->next->random=p->random->next;
}
auto dummy=new Node(-1);
auto cur=dummy;
for(auto p=head;p;p=p->next){//将两个表拆开
cur=cur->next=p->next;
p->next=p->next->next;
// auto q=p->next;
// cur=cur->next=q;
// p->next=q->next;
}
return dummy->next;
}