-
Notifications
You must be signed in to change notification settings - Fork 0
/
copy-list-with-random-pointer.cpp
52 lines (45 loc) · 1.54 KB
/
copy-list-with-random-pointer.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
/**
* 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 {
public:
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
RandomListNode *copyRandomList(RandomListNode *head) {
if (!head) return head;
map<RandomListNode*, RandomListNode*> nodes;
RandomListNode *newHead = new RandomListNode(head->label);
RandomListNode *current = newHead;
nodes[head] = current;
while (head && (head->next || head->random)) {
if (head->next) {
auto it = nodes.find(head->next);
if (it != nodes.end()) {
current->next = (*it).second;
} else {
current->next = new RandomListNode(head->next->label);
nodes[head->next] = current->next;
}
}
if (head->random) {
auto it = nodes.find(head->random);
if (it != nodes.end()) {
current->random = (*it).second;
} else {
current->random = new RandomListNode(head->random->label);
nodes[head->random] = current->random;
}
}
current = current->next;
head = head->next;
}
return newHead;
}
};