-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question40.cpp
45 lines (41 loc) · 1001 Bytes
/
Question40.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
40 -> Copy List with Random Pointer
Solution :
class Solution {
public:
void insertattail(Node*&head,Node*&tail,int data){
Node* newnode=new Node(data);
if(head==NULL){
head=newnode;
tail=newnode;
}
else{
tail->next=newnode;
tail=newnode;
}
}
Node* copyRandomList(Node* head) {
Node*curr=head;
Node*anshead=NULL;
Node*anstail=NULL;
while(curr){
insertattail(anshead,anstail,curr->val);
curr=curr->next;
}
curr=head;
Node*temp=anshead;
unordered_map<Node*,Node*>m;
while(curr&&temp){
m[curr]=temp;
curr=curr->next;
temp=temp->next;
}
curr=head;
temp=anshead;
while(temp){
temp->random=m[curr->random];
temp=temp->next;
curr=curr->next;
}
return anshead;
}
};