25.复杂链表的复制
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
1 class Solution { 2 public: 3 /* 4 1、复制每个节点,如:复制节点A得到A1,将A1插入节点A后面 5 2、遍历链表,A1->random = A->random->next; 6 3、将链表拆分成原链表和复制后的链表 7 */ 8 9 RandomListNode* Clone(RandomListNode* pHead) 10 { 11 if(!pHead) return NULL; 12 RandomListNode *currNode = pHead; 13 while(currNode){ 14 RandomListNode *node = new RandomListNode(currNode->label); 15 node->next = currNode->next; 16 currNode->next = node; 17 currNode = node->next; 18 } 19 currNode = pHead; 20 while(currNode){ 21 RandomListNode *node = currNode->next; 22 if(currNode->random){ 23 node->random = currNode->random->next; 24 } 25 currNode = node->next; 26 } 27 //拆分 28 RandomListNode *pCloneHead = pHead->next; 29 RandomListNode *tmp; 30 currNode = pHead; 31 while(currNode->next){ 32 tmp = currNode->next; 33 currNode->next =tmp->next; 34 currNode = tmp; 35 } 36 return pCloneHead; 37 } 38 };
1 //哈希表法 2 class Solution { 3 public: 4 RandomListNode* Clone(RandomListNode* pHead) 5 { 6 if(pHead==NULL) return NULL; 7 8 map<RandomListNode*,RandomListNode*> m; 9 RandomListNode* pHead1 = pHead; 10 RandomListNode* pHead2 = new RandomListNode(pHead1->label); 11 RandomListNode* newHead = pHead2; 12 m[pHead1] = pHead2; 13 while(pHead1){ 14 if(pHead1->next) pHead2->next = new RandomListNode(pHead1->next->label); 15 else pHead2->next = NULL; 16 pHead1 = pHead1->next; 17 pHead2 = pHead2->next; 18 m[pHead1] = pHead2; 19 } 20 21 pHead1 = pHead; 22 pHead2 = newHead; 23 while(pHead1){ 24 pHead2->random = m[pHead1->random]; 25 pHead1 = pHead1->next; 26 pHead2 = pHead2->next; 27 } 28 return newHead; 29 } 30 };