当前位置: 代码迷 >> 综合 >> LeetCode: Copy List with Random Pointer
  详细解决方案

LeetCode: Copy List with Random Pointer

热度:98   发布时间:2023-12-21 04:11:19.0

题目很简单,直接贴答案:


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;
}


  相关解决方案