方法一:
用哈希表来存随机指针的位置
方法二:
①复制链表中每个节点
②确定复制节点中随机指针的指向
③分离链表并恢复原链表
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* head)
{
auto dummy = new RandomListNode(-1);
auto p = head;
while(p){ //复制原链表
auto next = p->next;
auto q = new RandomListNode(p->label);
p->next = q;
q->next = next;
p = next;
}
p = head;
while(p){ //随机指针确定指向
if(p->random)
p->next->random = p->random->next;
p = p->next->next;
}
p = head;
auto cur = dummy;
while(p){ //分离链表
auto next = p->next->next;
cur->next = p->next;
cur = cur->next;
p->next = next;
p = next;
}
return dummy->next;
}
};