-
Notifications
You must be signed in to change notification settings - Fork 3
/
copyRandomList.cpp
46 lines (42 loc) · 1.14 KB
/
copyRandomList.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
// Example program
#include <iostream>
#include <unordered_map>
using namespace std;
struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
RandomListNode *copyRandomList(RandomListNode *head) {
// write your code here
if(head == NULL){
return NULL;
}
unordered_map<RandomListNode*, RandomListNode*> map;
RandomListNode dummy(-1);
dummy.next = head;
RandomListNode * prev = &dummy;
RandomListNode * node = head;
while(node != NULL){
prev->next = new RandomListNode(node->label);
map[node] = prev->next;
prev = prev->next;
node = node->next;
}
node = head;
while(node != NULL){
RandomListNode * newNode = map[node];
newNode->random = map[node->random];
node = node->next;
}
return map[head];
}
int main()
{
RandomListNode A(-1);
RandomListNode B(1);
A.next = &B;
RandomListNode * X = copyRandomList(&A);
cout << X->label<<endl;
return 0;
}