forked from garimasingh128/CP-DSA-Cpp-C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloneLinkedList.cpp
115 lines (91 loc) · 1.85 KB
/
cloneLinkedList.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
//Algorithm to Clone a linked list
//Written by PeeyushKumar
#include <iostream>
using namespace std;
struct node
{
int data;
node *next, *rand;
};
void traverse(node *head)
{
node *ptr = head;
while (ptr->next != NULL)
{
cout << ptr->data << ", ";
ptr = ptr->next;
}
cout << ptr->data << endl;
}
node *clone(node *head)
{
node *newhead, *ptr;
newhead = new node;
newhead->data = head->data;
ptr = newhead;
while (head->next != NULL)
{
head = head->next;
ptr->next = new node;
ptr = ptr->next;
ptr->data = head->data;
}
return newhead;
}
node *clone_rand(node *head)
{
node *newhead, *ptr, *newptr;
ptr = head;
while (ptr != NULL)
{
newptr = new node;
newptr->data = ptr->data;
newptr->next = ptr->next;
ptr->next = newptr;
ptr = newptr->next;
}
ptr = head;
while (ptr != NULL)
{
ptr->next->rand = ptr->rand->next;
ptr = ptr->next->next;
}
newhead = head->next;
newptr = newhead;
ptr = head;
while (ptr != NULL)
{
ptr->next = newptr->next;
ptr = ptr->next;
if (ptr != NULL)
newptr->next = ptr->next;
newptr = newptr->next;
}
return newhead;
}
int main()
{
node *head = new node;
head->data = 1;
node *ptr = new node;
ptr->data = 2;
head->next = ptr;
node *newnode = new node;
newnode->data = 3;
ptr->next = newnode;
ptr = ptr->next;
newnode = new node;
newnode->data = 4;
ptr->next = newnode;
ptr = ptr->next;
ptr->rand = head;
ptr = head;
ptr->rand = ptr->next->next;
ptr = ptr->next;
ptr->rand = ptr->next->next;
ptr->next->rand = ptr;
traverse(head);
node *x = clone_rand(head);
traverse(x);
return 0;
}