pgrm_028.cpp
Problem Statement
pgrm_028.cpp
Circluar linked list
Source Code
cpp
#include <iostream>
using namespace std;
struct Node {
int info;
Node *next = this;
};
class circularlist {
private:
Node *cl = nullptr;
public:
void insertEnd();
void display();
~circularlist();
};
typedef class circularlist cl;
void circularlist::insertEnd() {
Node *newNode = new Node;
cout << "Enter info: ";
cin >> newNode->info;
if (cl == nullptr) {
cl = newNode;
cl->next = cl;
} else {
newNode->next = cl->next;
cl->next = newNode;
cl = newNode;
}
cout << endl << "Inserted " << newNode->info << " at the end\n";
}
void circularlist::display() {
if (cl == nullptr) {
cout << "List is empty\n";
return;
}
Node *t = cl->next;
cout << "Circular List: ";
do {
cout << t->info << " -> ";
t = t->next;
} while (t != cl->next);
cout << "(head)\n";
}
circularlist::~circularlist() {
if (cl == nullptr) return;
Node *t = cl->next;
Node *p;
while (t != cl) {
p = t->next;
delete t;
t = p;
}
delete cl;
cl = nullptr;
}
int main() {
circularlist list;
int choice;
while (true) {
cout << "\n--- Circular Linked List Menu ---\n";
cout << "1. Insert at End\n";
cout << "2. Display List\n";
cout << "3. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
list.insertEnd();
break;
case 2:
list.display();
break;
case 3:
cout << "Exiting program...\n";
return 0;
default:
cout << "Invalid choice! Please try again.\n";
}
}
return 0;
}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
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