題目:
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
提示:
此題有兩種方法,一種是按照原鏈表next的順序依次創建節點,並處理好新鏈表的next指針,同時把原節點與新節點的對應關系保存到一個hash_map中,然后第二次循環將random指針處理好。這種方法的時間復雜度是O(n),空間復雜度也是O(n)。
第二種方法則是在原鏈表的每個節點之后插入一個新的節點,這樣原節點與新節點的對應關系就已經明確了,因此不需要用hash_map保存,但是需要第三次循環將整個鏈表拆分成兩個。這種方法的時間復雜度是O(n),空間復雜度是O(1)。
但是利用hash_map的方法具有其他的優點,如果在循環中加入一個判斷,就可以檢測出鏈表中是否有循環;而第二種方法則不行,會陷入死循環。
代碼:
使用hash_map的方法:
/** * 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) { if (!head) return NULL; unordered_map<RandomListNode*, RandomListNode*> mp; // 創建一個新的鏈表頭 RandomListNode *new_head = new RandomListNode(head->label); // node1負責指向原鏈表,node2負責指向新鏈表 RandomListNode *node1 = head, *node2 = new_head; /** * 按照原鏈表的結構不斷創建新的節點,並維護好next指針,將node1與node2的對應關系保存到hash_map中, * 以備后面維護random指針的時候,可以通過node1找到對應的node2。 */ while (node1->next != NULL) { mp[node1] = node2; node1 = node1->next; node2->next = new RandomListNode(node1->label); node2 = node2->next; } // 將兩個鏈表的尾巴的對應關系也保存好 mp[node1] = node2; // 繼續從頭開始處理random指針 node1 = head; node2 = new_head; while (node1->next != NULL) { node2->random = mp[node1->random]; node1 = node1->next; node2 = node2->next; } // 把尾巴的random指針也處理好 node2->random = mp[node1->random]; return new_head; } };
不使用hash_map的方法:
/** * 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) { /** * 假設:l1代表原鏈表中的節點;l2代表新鏈表中的節點 */ RandomListNode *new_head, *l1, *l2; if (head == NULL) return NULL; /** * 第一步:在每一個l1后面創建一個l2,並讓l1指向l2,l2指向下一個l1; */ for (l1 = head; l1 != NULL; l1 = l1->next->next) { l2 = new RandomListNode(l1->label); l2->next = l1->next; l1->next = l2; } /** * 第二步:給l2的random賦值,l1的random的next指向的就是l2的random的目標; */ new_head = head->next; for (l1 = head; l1 != NULL; l1 = l1->next->next) { if (l1->random != NULL) l1->next->random = l1->random->next; } /** * 第三步:需要將整個鏈表拆成兩個鏈表,具體做法是讓l1的next指向后面的后面; * l2的next也指向后面的后面。 */ for (l1 = head; l1 != NULL; l1 = l1->next) { l2 = l1->next; l1->next = l2->next; if (l2->next != NULL) l2->next = l2->next->next; } return new_head; } };