复杂链表的复制
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路:N'连接在N的后面,可以以O(n)的时间复制特殊指针的指向,再将两个链表分离
1 void cloneList(RandomListNode *pHead) 2 { 3 while(pHead) 4 { 5 RandomListNode *p=pHead->next; 6 pHead->next=new RandomListNode(pHead->label); 7 pHead->next->next=p; 8 pHead=p; 9 } 10 } 11 void cloneRandom(RandomListNode *pHead) 12 { 13 while(pHead) 14 { 15 if(pHead->random) 16 { 17 pHead->next->random=pHead->random->next; 18 } 19 pHead=pHead->next->next; 20 } 21 } 22 RandomListNode * departList(RandomListNode *pHead) 23 { 24 RandomListNode *newHead=pHead->next; 25 RandomListNode *tmp=newHead; 26 while(tmp->next) 27 { 28 pHead->next=tmp->next; 29 pHead=pHead->next; 30 tmp->next=pHead->next; 31 tmp=tmp->next; 32 } 33 pHead->next=tmp->next; 34 return newHead; 35 } 36 RandomListNode* Clone(RandomListNode* pHead) 37 { 38 if(pHead==NULL)return NULL; 39 cloneList(pHead); 40 cloneRandom(pHead); 41 return departList(pHead); 42 }
好吧,递归的写法竟然会超时
1 class Solution { 2 public: 3 void CloneNodes(RandomListNode *pHead) 4 { 5 if(pHead==NULL)return; 6 RandomListNode *tmp=new RandomListNode(pHead->label); 7 tmp->next=pHead->next; 8 pHead->next=tmp; 9 CloneNodes(tmp->next); 10 } 11 void CloneRandomNodes(RandomListNode *pHead) 12 { 13 while(pHead) 14 { 15 if(pHead->random)pHead->next->random=pHead->random->next; 16 else pHead->next->random=NULL; 17 pHead=pHead->next->next; 18 } 19 } 20 RandomListNode * ReconnectNodes(RandomListNode *pHead) 21 { 22 if(pHead==NULL)return NULL; 23 RandomListNode *tmpHead=pHead->next; 24 pHead->next=tmpHead->next; 25 tmpHead->next=ReconnectNodes(pHead->next); 26 return tmpHead; 27 } 28 RandomListNode* Clone(RandomListNode* pHead) 29 { 30 CloneNodes(pHead); 31 CloneRandomNodes(pHead); 32 return ReconnectNodes(pHead); 33 } 34 };