-
Notifications
You must be signed in to change notification settings - Fork 656
/
Copy pathcloneLinkedListCPP
64 lines (52 loc) · 1.43 KB
/
cloneLinkedListCPP
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
58
59
60
61
62
63
64
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
Node *iter = head;
Node *front = head;
// First round: make copy of each node,
// and link them together side-by-side in a single list.
while (iter != NULL) {
front = iter->next;
Node *copy = new Node(iter->val);
iter->next = copy;
copy->next = front;
iter = front;
}
// Second round: assign random pointers for the copy nodes.
iter = head;
while (iter != NULL) {
if (iter->random != NULL) {
iter->next->random = iter->random->next;
}
iter = iter->next->next;
}
// Third round: restore the original list, and extract the copy list.
iter = head;
Node *pseudoHead = new Node(0);
Node *copy = pseudoHead;
while (iter != NULL) {
front = iter->next->next;
// extract the copy
copy->next = iter->next;
// restore the original list
iter->next = front;
copy = copy -> next;
iter = front;
}
return pseudoHead->next;
}
};