-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathCopyListWithRandomPointer.cpp
More file actions
68 lines (64 loc) · 1.42 KB
/
CopyListWithRandomPointer.cpp
File metadata and controls
68 lines (64 loc) · 1.42 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
66
67
68
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution
{
public:
Node* insert_tail(Node *head, int val)
{
Node *ptr = new Node(val);
Node *temp = head;
if (head == NULL)
{
head = ptr;
return head;
}
while (temp->next)
{
temp = temp->next;
}
temp->next = ptr;
return head;
}
Node* copyRandomList(Node *head)
{
//step 1: create clone linked list
Node *clone = NULL;
Node *temp = head;
while (temp)
{
clone = insert_tail(clone, temp->val);
temp = temp->next;
}
//step 2: create map
temp = head;
Node *temp1 = clone;
unordered_map<Node*, Node*> mapping;
while (temp)
{
mapping[temp] = temp1;
temp = temp->next;
temp1 = temp1->next;
}
temp1 = clone;
temp = head;
while (temp)
{
temp1->random = mapping[temp->random];
temp = temp->next;
temp1 = temp1->next;
}
return clone;
}
};