复杂链表的复制
复杂链表的复制
https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba?tpId=13&tqId=11178&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
/* struct RandomListNode { int label; struct RandomListNode *next, *random; RandomListNode(int x) : label(x), next(NULL), random(NULL) { } }; */ class Solution { public: RandomListNode* Clone(RandomListNode* pHead) { int count=0; if(pHead==NULL) return NULL; RandomListNode* p=pHead; //插入新节点 while(p) { count++; int val=p->label; RandomListNode* node=new RandomListNode(val); node->next=p->next; p->next=node; p=node->next; } RandomListNode* newHead=pHead->next; p=pHead; while(p) { if(p->random) { p->next->random=p->random->next; } p=p->next->next; } p=pHead; RandomListNode* p2=newHead; while(--count) { p->next=p2->next; p2->next=p2->next->next; p=p->next; p2=p2->next; } p->next=NULL; p2->next=NULL; return newHead; } };
分三步
/*
1、复制每个节点,如:复制节点A得到A1,将A1插入节点A后面
2、遍历链表,A1->random = A->random->next;
3、将链表拆分成原链表和复制后的链表
*/
注意第二步p->next->random=p->random->next;中要先保证p->random不为空才能获得p->random->next;