-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path113makecircularwithrandomnode.cpp
More file actions
85 lines (66 loc) · 1.34 KB
/
Copy path113makecircularwithrandomnode.cpp
File metadata and controls
85 lines (66 loc) · 1.34 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
#include <iostream>
using namespace std;
struct Node {
int data;
Node* prev;
Node* next;
Node(int val) {
data = val;
prev = nullptr;
next = nullptr;
}
};
Node* makeCircular(Node* pnode){
if(!pnode) return nullptr;
Node* tail = pnode;
Node* head = pnode;
while(head->prev){
head = head->prev;
}
while(tail->next){
tail = tail->next;
}
head->prev = tail;
tail->next = head;
return head;
}
void traverseForward(Node* head) {
Node* temp = head;
while (temp) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
void traverseCircular(Node* head) {
if (!head) return;
Node* temp = head;
do {
cout << temp->data << " ";
temp = temp->next;
} while (temp != head);
cout << endl;
}
int main() {
/*
Create DLL:
1 <-> 2 <-> 3 <-> 4
*/
Node* n1 = new Node(1);
Node* n2 = new Node(2);
Node* n3 = new Node(3);
Node* n4 = new Node(4);
n1->next = n2;
n2->prev = n1;
n2->next = n3;
n3->prev = n2;
n3->next = n4;
n4->prev = n3;
cout << "Normal DLL: ";
traverseForward(n1);
// Random node given (say n3)
Node* head = makeCircular(n3);
cout << "Circular DLL: ";
traverseCircular(head);
return 0;
}