题目很简单,直接贴答案:
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;
}