-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathCopyComplexList.cpp
48 lines (48 loc) · 1.28 KB
/
CopyComplexList.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* head)
{
if (head==NULL) return NULL;
RandomListNode* cur = head;
//复制next 如原来是A->B->C 变成A->A'->B->B'->C->C'
while(cur)
{
RandomListNode* temp = new RandomListNode(cur->label);
temp->next = cur->next;
cur->next = temp;
cur = temp->next;
}
cur = head;
//复制random cur是原来链表的结点 cur->next是复制cur的结点
while(cur)
{
RandomListNode* temp = cur->next;
if (cur->random)
{
temp->random = cur->random->next;
}
cur = temp->next;
}
// 拆分链表,将链表拆分为原链表和复制后的链表
cur = head;
RandomListNode* p = head->next;
while(cur)
{
RandomListNode* temp = cur->next;
cur->next = temp->next;
if (temp->next!=NULL)
temp->next = temp->next->next;
cur = cur->next;
}
return p;
}
};