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.
Hash Table
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
RandomListNode *iter=head;
while(iter!=NULL){ //每个复制一个放于身后
RandomListNode *tone=new RandomListNode(iter->label), *tnext;
tnext=iter->next;
iter->next = tone;
tone->next = tnext;
iter=tnext;
}
iter=head;
while(iter!=NULL){ //复制random
if(iter->random!=NULL){
iter->next->random=iter->random->next;
}
iter=iter->next->next;
}
iter=head;
RandomListNode *copy = new RandomListNode(0), *copy1, *copy2 = copy; //三个指针是必要的,你不清楚iter->next->next->next是否为空
while(iter!=NULL){ //把两张表拆分开来
copy1=iter->next;
iter->next=iter->next->next;
copy2->next=copy1;
iter=iter->next;
copy2=copy1;
}
return copy->next;
}
};