-
Notifications
You must be signed in to change notification settings - Fork 0
/
20180126clone.cpp
54 lines (54 loc) · 1.5 KB
/
20180126clone.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
49
50
51
52
53
54
/*
struct RandomListNode {
int label;
struct RandomListNode *next, *random;
RandomListNode(int x) :
label(x), next(NULL), random(NULL) {
}
};
*/
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
clonenode(pHead);
clonerandom(pHead);
return connect(pHead);
}
void clonenode(RandomListNode* pHead){
RandomListNode *pnode=pHead;
while(pnode!=NULL){
RandomListNode *pclone=new RandomListNode(pnode->label);
pclone->next=pnode->next;
pclone->random=NULL;
pnode->next=pclone;
pnode=pclone->next;
}
}
void clonerandom(RandomListNode* pHead){
RandomListNode *pnode=pHead;
while(pnode!=NULL){
RandomListNode* pclonenode=pnode->next;
if(pnode->random!=NULL)
pclonenode->random=pnode->random->next;
pnode=pclonenode->next;
}
}
RandomListNode* connect(RandomListNode* pHead){
RandomListNode *pnode=pHead;
RandomListNode *pclonehead=NULL;
RandomListNode *pclonenode=NULL;
if(pnode!=NULL){
pclonehead=pclonenode=pnode->next;
pnode->next=pclonenode->next;
pnode=pnode->next;
}
while(pnode!=NULL){
pclonenode->next=pnode->next;
pclonenode=pclonenode->next;
pnode->next=pclonenode->next;
pnode=pnode->next;
}
return pclonehead;
}
};