第一次遍歷鏈表的時候,複製舊鏈表的節點值創建一個新的鏈表,同時定義一個 unordered_map 做爲哈希表,哈希表的鍵爲舊鏈表的節點指針,值爲新鏈表的節點指針。node
而後,第二次遍歷鏈表,訪問舊鏈表節點的隨機指針,而後以此爲鍵從 map 中取出對應的新鏈表節點指針,這也就是當前新鏈表節點的隨機指針。dom
/** * 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); //哨兵節點,方便操做 RandomListNode *copy_temp = new_head; // 創建新鏈表 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; // 填充新鏈表的隨機指針 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; } };
獲取更多精彩,請關注「seniusen」! spa