-
Notifications
You must be signed in to change notification settings - Fork 0
/
050_CloneLinkedListWithRandomPointer.cpp
53 lines (43 loc) · 1.25 KB
/
050_CloneLinkedListWithRandomPointer.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
53
#include<bits/stdc++.h>
using namespace std;
/*************************************************************
Following is the LinkedListNode class structure
*************************************************************/
template <typename T>
class LinkedListNode
{
public:
T data;
LinkedListNode<T> *next;
LinkedListNode<T> *random;
LinkedListNode(T data)
{
this->data = data;
this->next = NULL;
}
};
LinkedListNode<int> *cloneRandomList(LinkedListNode<int> *head)
{
// Write your code here.
LinkedListNode<int> *dummy=new LinkedListNode<int>(0);
LinkedListNode<int> *newHead=dummy;
LinkedListNode<int> *ptr=head;
map<LinkedListNode<int>*, LinkedListNode<int>*> nodes;
while(ptr){
LinkedListNode<int> *newNode=new LinkedListNode<int>(ptr->data);
nodes[ptr]=newNode;
newHead->next=newNode;
ptr=ptr->next;
newHead=newHead->next;
}
newHead=dummy->next;
ptr=head;
while(newHead){
newHead->random=ptr->random?nodes[ptr->random]:NULL;
// cout<<newHead->data<<" "<<(newHead->random?newHead->random->data:-1)<<" ";
newHead=newHead->next;
ptr=ptr->next;
}
// cout<<endl;
return dummy->next;
}