26 复杂链表的复制

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的 head。

C++:

 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 public:
12     RandomListNode* Clone(RandomListNode* pHead)
13     {
14         if (pHead == NULL)
15             return NULL ;
16         // 插入新节点
17         RandomListNode* cur = pHead ;
18         while(cur != NULL){
19             RandomListNode* clone = new RandomListNode(cur->label) ;
20             clone->next = cur->next ;
21             clone->random = NULL ;
22             
23             cur->next = clone ;
24             cur = clone->next ;
25         }
26         
27         // 建立 random 链接
28         cur = pHead ;
29         while(cur != NULL){
30             RandomListNode* clone = cur->next ;
31             if (cur->random != NULL){
32                 clone->random = cur->random->next ;
33             }
34             cur = clone->next ;
35         }
36         
37         // 拆分
38         cur = pHead ;
39         RandomListNode* pCloneHead = pHead->next ;
40         while(cur->next != NULL){
41             RandomListNode* p = cur->next ;
42             cur->next = p->next ;
43             cur = p ;
44         }
45         return pCloneHead ;
46     }
47 };
原文地址:https://www.cnblogs.com/mengchunchen/p/8991103.html