题解 | #复杂链表的复制#
复杂链表的复制
http://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba
或许你和我一样,题目拿到手先想到的是用map来映射每一个值对应的节点,劈里啪啦代码敲了半天,段错误QAQ
对着题解比较了半天发现大家思路都一样啊,仔细看了好久才看出来坑在哪:
1、点此查看相关讯息 里有写了,lable是不会重复的
2、不是每一个节点都存在random指针的,要做一个是否存在的判断
兄弟们,要认真读题啊
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead) {
if(pHead == NULL) return NULL;
map<int,RandomListNode*> cache;
RandomListNode *root = pHead,*ansroot = new RandomListNode(pHead->label),*ans=ansroot;
cache[pHead->label] = ansroot;
while(pHead->next!=nullptr)//复制链表到ansroot
{
pHead = pHead->next;
RandomListNode* temp = new RandomListNode(pHead->label);
temp->next = pHead->next;
ans->next = temp;
cache[pHead->label] = temp;
ans = ans->next;
}
//处理随机节点指针
pHead = root;
RandomListNode *r = ansroot;
while(pHead != nullptr)
{
if(pHead->random!=nullptr)//不是所有节点都有random指针
{
r->random = cache[pHead->random->label];
}
r = r->next;
pHead = pHead->next;
}
return ansroot;
}
};