-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path26.复杂链表的复制.cpp
More file actions
57 lines (54 loc) · 1.38 KB
/
26.复杂链表的复制.cpp
File metadata and controls
57 lines (54 loc) · 1.38 KB
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
49
50
51
52
53
54
55
56
57
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead){
if(pHead == NULL) return NULL;
cloneNodes(pHead);
connectRandom(pHead);
return connectNext(pHead);
}
private:
void cloneNodes(RandomListNode* head){
RandomListNode *p = head;
while(p != NULL){
RandomListNode *node = new RandomListNode(p->label);
node->next = p->next;
p->next = node;
//循环
p = node->next;
}
}
void connectRandom(RandomListNode* head){
RandomListNode *p = head;
while(p != NULL){
if(p->random != NULL)
p->next->random = p->random->next;
p = p->next->next;
}
}
RandomListNode* connectNext(RandomListNode* head){
RandomListNode *clonedHead = head->next;
RandomListNode *p = head;
RandomListNode *q = clonedHead;
//p先走一步
if(p != NULL){
p->next = q->next;
p = p->next;
}
while(p != NULL){
q->next = p->next;
q = q->next;
p->next = q->next;
p = p->next;
}
return clonedHead;
}
};