另一种方法(C++)
复杂链表的复制
http://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba
/*
struct RandomListNode {
int label;
struct RandomListNode next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode Clone(RandomListNode* pHead)
{
if(!pHead)//判断头指针为空
return pHead;
RandomListNode* res = new RandomListNode(-1);//创建新头指针
RandomListNode* ph = pHead;
map<RandomListNode*,int> m1;//记录旧链表地址映射关系
map<int,RandomListNode*> m2;//记录新链表地址映射关系
RandomListNode* cur;
RandomListNode* head = res;
int i = 0;
while(pHead){//复制主体链表
cur = new RandomListNode(-1);
cur->label = pHead->label;
m1[pHead]=i;
m2[i]=cur;
++i;
head->next=cur;
head = head->next;
pHead = pHead->next;
}
head->next = nullptr;
for(int j=0;j<i;++j){//添加随机指针部分
if(!ph->random)
m2[j]->random=nullptr;
else{
int index = m1.find(ph->random)->second;
m2[j]->random=m2[index];
}
ph=ph->next;
}
return res->next;
}};
