-
Notifications
You must be signed in to change notification settings - Fork 0
/
CopyListWithRandomPointer.cpp
50 lines (46 loc) · 1.13 KB
/
CopyListWithRandomPointer.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
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node() {}
Node(int _val, Node* _next, Node* _random) {
val = _val;
next = _next;
random = _random;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head == NULL){
return NULL;
}
Node * curr = head;
while(curr){
Node * temp = new Node(curr->val);
temp->next = curr->next;
curr->next = temp;
curr = temp->next;
temp->random = NULL;
}
curr = head;
while(curr ){
curr->next->random = curr->random != NULL ? curr->random->next : NULL;
curr = curr->next->next;
}
curr = head;
Node * curr_new = head->next;
Node * result = head->next;
while(curr!= NULL){
curr->next = curr->next->next;
curr_new->next = curr_new->next != NULL ? curr_new->next->next : NULL;
curr = curr->next;
curr_new = curr_new->next;
}
return result;
}
};