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.
思路1:最傻瓜的方法是首先遍歷一次建立next關系的新list。然后第二次遍歷處理random關系,對于每個有random結點的node,我們都從表頭開始遍歷尋找其random的結點。然后給新list的相應結點賦值。這種話對于每個node,尋找random須要花費O(N)時間。故總時間復雜度為O(N^2)。這個方案會超時。
思路2:改進思路1。假設處理random關系的復制,使其復雜度降為O(N)?答案是要找到原node的random指向的結點在新list中相應的那個結點,假設能一下找到,那么就攻克了;實現方法是使用一個map<old, new>。記錄原node與新node的相應關系。然后進行兩次遍歷,第一次建立next關系的新list。第二次給新list建立random指向關系;代碼例如以下:
/*** 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) {map<RandomListNode *, RandomListNode *> mapNodes;RandomListNode *newList = NULL;RandomListNode *newHead = NULL;RandomListNode *p = head;if(head==NULL)return NULL;while(p!=NULL){RandomListNode *q = new RandomListNode(p->label);mapNodes[p] = q;if(newHead==NULL){newHead = q;newList = q; }else{newList->next = q;newList = newList->next;}p = p->next; }p = head;newList = newHead;while(p!=NULL){if(p->random!=NULL)newList->random = mapNodes[p->random]; //注意這里要用p->random而不是pp = p->next;newList = newList->next;}return newHead; //返回值是newHead而不是newList,由于此時newList指向尾部}
};
思路3:思路2沒有改變原list結構,可是使用了map,故須要額外的內存空間,假設原list解構可變。那么能夠不必使用map記錄映射關系,而是直接把復制的node放在原node的后面,這樣結構變為:
上面為第一次遍歷,第二次遍歷時把紅色的新node的random域賦值。規則是:
newNode->ranodm = oldNode->random->next;
然后第三次遍歷把上面的鏈表拆分為兩個就可以。代碼例如以下:
/*** 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) {RandomListNode *newList = NULL;RandomListNode *newHead = NULL;RandomListNode *p = head;if(head==NULL)return NULL;while(p!=NULL){RandomListNode *q = new RandomListNode(p->label);q->next = p->next;p->next = q;p = q->next;}p = head;while(p!=NULL){if(p->random != NULL)p->next->random = p->random->next;p = p->next->next;}p = head;while(p!=NULL && p->next!=NULL){ //注意這里的條件,首先要推斷p是否為nullif(p==head){newHead = p->next;newList = newHead;}else{newList->next = p->next;newList = newList->next;}p->next = newList->next;p = p->next;}return newHead; //返回值是newHead而不是newList,由于此時newList指向尾部}
};
參考鏈接:http://www.2cto.com/kf/201310/253477.html