1 class Solution {
2 public:
3 Node* copyRandomList(Node* head)
4 {
5 if (head == NULL)
6 {
7 return head;
8 }
9 Node *cur = head;
10 Node *copy = NULL;
11 Node *temp = NULL;
12
13 while (cur != NULL)
14 {
15 temp = cur->next; //保存原结点的下一个结点
16 copy = new Node(cur->val); //创建新结点
17 copy->next = cur->next; //复制结点的下一个结点为原结点下一个结点
18 cur->next = copy; //原结点下一个结点是复制结点
19 cur = temp; //跳到下一个原结点继续遍历
20 }
21 cur = head;
22 copy = NULL;
23 // while (cur != NULL)
24 // {
25 // copy = cur->next->next; //原结点下一个结点
26 // //当前复制结点,找到下一个复制结点
27 // cur->next->next = (copy != NULL)? copy->next:NULL;
28 // //当前复制结点为当前原结点的自由结点的下一个结点 A-a-B-b-C-c-null;
29 // cur->next->random = (cur->random != NULL)? cur->random->next:NULL;
30 // cur = copy;
31 // }
32 while(cur != NULL)
33 {
34 copy = cur->next;
35 if(cur->random)
36 copy->random = cur->random->next;
37 else
38 copy->random = NULL;
39 cur=copy->next;
40 }
41 cur = head;
42 copy = head->next;
43 Node *copy_cur = head->next;
44 while(cur != NULL)
45 {
46 cur->next = cur->next->next;
47 cur = cur->next;
48 if (copy_cur->next != NULL)
49 {
50 copy_cur->next = copy_cur->next->next;
51 copy_cur = copy_cur->next;
52 }
53 }
54 return copy;
55 }
56 };