题目很简单,直接贴答案:
RandomListNode *copyRandomList(RandomListNode *head) {
if (!head){
return NULL;
}
RandomListNode* cur = head;
RandomListNode* result = new RandomListNode(head->label);
RandomListNode* resCur = result;
unordered_map<RandomListNode*, RandomListNode*> nodes;
nodes.insert(make_pair(cur, resCur));
nodes.insert(make_pair((RandomListNode*)NULL, (RandomListNode*)NULL));
while (cur->next){
auto next = cur->next;
auto random = cur->random;
auto it = nodes.find(next);
if (it == nodes.end()){
RandomListNode* tmp = new RandomListNode(next->label);
nodes.insert(make_pair(next, tmp));
resCur->next = tmp;
}
else{
resCur->next = it->second;
}
it = nodes.find(random);
if (it == nodes.end()){
RandomListNode* tmp = new RandomListNode(random->label);
nodes.insert(make_pair(random, tmp));
resCur->random = tmp;
}
else{
resCur->random = it->second;
}
cur = cur->next;
resCur = resCur->next;
}
auto it = nodes.find(cur->random);
resCur->random = it->second;
resCur->next = NULL;
return result;
}

本文提供了一种使用哈希表方法来深拷贝带有随机指针的复杂链表的具体实现。通过迭代原始链表并利用unordered_map来跟踪节点对应关系,确保了每个节点及其随机指针都能正确复制。
1266

被折叠的 条评论
为什么被折叠?



