-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCloneaLinkedListwithnextandRandomPointer.cpp
More file actions
101 lines (85 loc) · 2.02 KB
/
CloneaLinkedListwithnextandRandomPointer.cpp
File metadata and controls
101 lines (85 loc) · 2.02 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
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
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *next, *random;
Node(int x) {
data = x;
next = random = NULL;
}
};
Node* cloneLinkedList(Node* head) {
if (head == NULL) {
return NULL;
}
// Step 1: Create new nodes and insert them next to the original nodes
Node* curr = head;
while (curr != NULL) {
Node* newNode = new Node(curr->data);
newNode->next = curr->next;
curr->next = newNode;
curr = newNode->next;
}
// Step 2: Set the random pointers of the new nodes
curr = head;
while (curr != NULL) {
if (curr->random != NULL) {
curr->next->random = curr->random->next;
}
curr = curr->next->next;
}
// Step 3: Separate the new nodes from the original nodes
curr = head;
Node* clonedHead = head->next;
Node* clonedCurr = clonedHead;
while (clonedCurr->next != NULL) {
curr->next = curr->next->next;
clonedCurr->next = clonedCurr->next->next;
curr = curr->next;
clonedCurr = clonedCurr->next;
}
curr->next = NULL;
clonedCurr->next = NULL;
return clonedHead;
}
// Function to print the linked list
void printList(Node* head)
{
cout << head->data << "("
<< head->random->data << ")";
head = head->next;
while (head != NULL) {
cout << " -> " << head->data << "("
<< head->random->data << ")";
head = head->next;
}
cout << endl;
}
// Driver code
int main()
{
// Creating a linked list with random pointer
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next
= new Node(5);
head->random = head->next->next;
head->next->random = head;
head->next->next->random
= head->next->next->next->next;
head->next->next->next->random
= head->next->next;
head->next->next->next->next->random
= head->next;
// Print the original list
cout << "The original linked list:\n";
printList(head);
// Function call
Node* sol = cloneLinkedList(head);
cout << "The cloned linked list:\n";
printList(sol);
return 0;
}