-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy_list_with_random_pointer.cpp
More file actions
37 lines (34 loc) · 1.11 KB
/
Copy pathcopy_list_with_random_pointer.cpp
File metadata and controls
37 lines (34 loc) · 1.11 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
/**
* 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) {
// write your code here
unordered_map<RandomListNode *, RandomListNode *> hashTable;
RandomListNode *temp = head;
while (temp != NULL) {
RandomListNode *copy = new RandomListNode(temp->label);
hashTable.insert({temp, copy});
temp = temp->next;
}
temp = head;
while (temp != NULL) {
if (temp->random != NULL)
hashTable[temp]->random = hashTable[temp->random];
if (temp->next != NULL)
hashTable[temp]->next = hashTable[temp->next];
temp = temp->next;
}
return hashTable[head];
}
};