-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopyLinkedList.cpp
More file actions
65 lines (43 loc) · 1.56 KB
/
copyLinkedList.cpp
File metadata and controls
65 lines (43 loc) · 1.56 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
58
59
60
61
62
63
64
65
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
private:
unordered_map<RandomListNode*, RandomListNode*> myHash;
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(!head) return NULL;
RandomListNode *curr = head, *ahead, *newHead ;
//Changed A->B to A->A'->B->B'
while(curr){
ahead = curr->next;
RandomListNode *copy = new RandomListNode(curr->label);
copy->next = curr->next;
curr->next = copy;
curr = ahead;
}
// Now have to copy the random pointers of all the original nodes
curr = head;
newHead = head->next;
while(curr){
if(curr->random){
curr->next->random = curr->random->next;
}
curr = curr->next->next;
}
//Detaching the list from new list
curr = head;
while(curr){
ahead = curr->next;
curr->next = ahead->next;
if (ahead->next != NULL) ahead->next = ahead->next->next;
curr = curr->next;
}
return newHead;
}
};