1. topic
2. answers
When traversing the list for the first time, copy the node values of the old list to create a new list, and define an unordered map as the hash table. The key of the hash table is the node pointer of the old list and the value is the node pointer of the new list.
Then, traverse the list for the second time, access the random pointer of the old list node, and then take the corresponding new list node pointer from the map as the key, which is the random pointer of the current new list node.
/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label; * RandomListNode *next, *random; * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */ class Solution { public: RandomListNode *copyRandomList(RandomListNode *head) { unordered_map<RandomListNode *, RandomListNode *> nodemap; RandomListNode *temp = head; RandomListNode *new_head = new RandomListNode(0); //Sentinel node, easy to operate RandomListNode *copy_temp = new_head; // Create a new linked list while (temp) { copy_temp->next = new RandomListNode(temp->label); nodemap[temp] = copy_temp->next; temp = temp->next; copy_temp = copy_temp->next; } RandomListNode *random_temp = NULL; temp = head; copy_temp = new_head->next; // Random pointer to fill new linked list while (temp) { random_temp = temp->random; if (random_temp != NULL) copy_temp->random = nodemap[random_temp]; else copy_temp->random = NULL; temp = temp->next; copy_temp = copy_temp->next; } return new_head->next; } };
For more highlights, please pay attention to "seniusen"!