您的位置:首页 > 运维架构

LeetCode: Copy List with Random Pointer

2014-11-25 22:35 274 查看
题目很简单,直接贴答案:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ leetcode