1 /* 2 struct RandomListNode { 3 int label; 4 struct RandomListNode *next, *random; 5 RandomListNode(int x) : 6 label(x), next(NULL), random(NULL) { 7 } 8 }; 9 */ 10 class Solution 11 { 12 public: 13 //在旧链表中创建新链表,此时不处理新链表的兄弟结点 14 void CloneNode(RandomListNode* pHead) 15 { 16 RandomListNode* pNode = pHead; 17 while(pNode != NULL) 18 { 19 RandomListNode* newNode = new RandomListNode(pNode->label); 20 newNode->next = pNode->next; 21 22 pNode->next = newNode; 23 pNode = newNode->next; 24 } 25 } 26 //根据旧链表的random结点,初始化新链表的random结点 27 void CloneRandomNode(RandomListNode* pHead) 28 { 29 RandomListNode* pNode = pHead; 30 while(pNode != NULL) 31 { 32 RandomListNode* pNewNode = pNode->next; 33 if(pNode->random != NULL) 34 pNewNode->random = pNode->random->next; 35 pNode = pNewNode->next; 36 } 37 } 38 //从旧链表中拆分得到新链表 39 RandomListNode* getNewList(RandomListNode* pHead) 40 { 41 RandomListNode* pNode = pHead; 42 RandomListNode* pClonedHead = pHead->next; 43 RandomListNode* pClonedNode = pHead->next; 44 45 pNode->next = pClonedNode->next; 46 pNode = pNode->next; 47 48 //循环 49 while(pNode!=NULL) 50 { 51 pClonedNode->next = pNode->next; 52 pClonedNode = pClonedNode->next; 53 pNode->next = pClonedNode->next; 54 pNode = pNode->next; 55 } 56 return pClonedHead; 57 } 58 RandomListNode* Clone(RandomListNode* pHead) 59 { 60 if(pHead==NULL) return NULL; 61 CloneNode(pHead); 62 CloneRandomNode(pHead); 63 return getNewList(pHead); 64 } 65 };