-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclone of linked list.cpp
93 lines (81 loc) · 2.09 KB
/
clone of linked list.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* next,*random;
Node(int data) //parametarised constructor
{
this->data=data;
this->next=NULL;
this->random=NULL;
}
};
class Node1{
public:
Node* head;
Node1(Node* head){
this->head=head;
}
void push(int data){
Node* temp=new Node(data);
temp->data=data;
temp->next=head;
head=temp;
}
void print()
{
Node *temp = head;
while (temp != NULL)
{
Node *random = temp->random;
int randomData = (random != NULL)?
random->data: -1;
cout << "Data = " << temp->data
<< ", ";
cout << "Random Data = " <<
randomData << endl;
temp = temp->next;
}
cout << endl;
}
Node1* clone()
{
Node *origCurr = head;
Node *clone = NULL;
unordered_map<Node*, Node*> mymap;
while (origCurr != NULL)
{
cloneCurr = new Node(origCurr->data);
mymap[origCurr] = cloneCurr;
origCurr = origCurr->next;
}
origCurr = head;
while (origCurr != NULL)
{
cloneCurr = mymap[origCurr];
cloneCurr->next = mymap[origCurr->next];
cloneCurr->random = mymap[origCurr->random];
origCurr = origCurr->next;
}
return new LinkedList(mymap[head]);
}
};
int main()
{
Node1 *mylist = new LinkedList(new Node(5));
mylist->push(4);
mylist->push(3);
mylist->push(2);
mylist->push(1);
mylist->head->random = mylist->head->next->next;
mylist->head->next->random =mylist->head->next->next->next;
mylist->head->next->next->random =mylist->head->next->next->next->next;
mylist->head->next->next->next->random = mylist->head->next->next->next->next->next;
mylist->head->next->next->next->next->random =mylist->head->next;
Node1 *clone = mylist->clone();
cout << "Original linked list\n";
mylist->print();
cout << "\nCloned linked list\n";
clone->print();
}