138 Copy List with Random Pointer
RandomListNode *copyRandomList(RandomListNode *head) {
if (!head) return nullptr;
unordered_map<RandomListNode*, RandomListNode*> rand_memory;
RandomListNode *iter = head;
while (iter) {
rand_memory.insert({iter, new RandomListNode(iter->label) });
iter = iter->next;
}
iter = head;
while (iter) {
rand_memory[iter]->next = rand_memory[iter->next];
rand_memory[iter]->random = rand_memory[iter->random];
iter = iter->next;
}
return rand_memory[head];
}Last updated