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;
}
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;
}
相关文章推荐
- Copy List with Random Pointer 复制有随机指针的链表@LeetCode
- [leetcode]Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- LeetCode: Copy List with Random Pointer
- LeetCode — Copy List with Random Pointer 解题报告
- [LeetCode] Copy List with Random Pointer, Solution
- leetcode Copy List with Random Pointer
- LeetCode - Copy List with Random Pointer
- leetcode-Copy List with Random Pointer
- Leetcode: Copy List with Random Pointer
- LeetCode-Copy List with Random Pointer
- [LeetCode] Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- [leetcode]Copy List with Random Pointer
- Copy List with Random Pointer [LeetCode]
- leetcode -- Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- LeetCode(138)Copy List with Random Pointer
- [LeetCode]Copy List with Random Pointer
- leetcode - Copy List with Random Pointer