-
Notifications
You must be signed in to change notification settings - Fork 0
/
8circular_LL.cpp
145 lines (128 loc) · 3.23 KB
/
8circular_LL.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
// 8. Implement Circular Linked List ADT.
// Theory:
// This code implements a circular singly linked list data structure
// with functionalities to append elements to the list, display the
// elements in the list, and clear the list. It utilizes a Node class
// to represent individual elements and a circularlist class to manage
// the list operations. The main function provides a menu-driven
// interface for users to interact with the list.
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node* next;
Node(int value)
{
data = value;
next = nullptr;
}
};
class circularlist
{
private:
Node* head;
public:
circularlist()
{
head = nullptr;
}
void append(int value)
{
Node* newNode = new Node(value);
if (head == nullptr)
{
head = newNode;
head->next = head;
}
else
{
Node* current = head;
while (current->next != head)
{
current = current->next;
}
current->next = newNode;
newNode->next = head;
}
cout << value << " appended to the list." << endl;
}
void display()
{
if (head == nullptr)
{
cout << "list is empty." << endl;
return;
}
cout << "elements in list: ";
Node* current = head;
do
{
cout << current->data << " ";
current = current->next;
}
while (current != head);
cout << endl;
}
void clear()
{
if (head == nullptr)
{
cout << "list is empty." << endl;
return;
}
Node* current = head;
while (current->next != head)
{
Node* temp = current;
current = current->next;
delete temp;
}
delete current;
head = nullptr;
cout << "list cleared." << endl;
}
};
int main()
{
circularlist list;
int choice, data;
do
{
cout << "\n1. append\n";
cout << "2. display\n";
cout << "3. clear\n";
cout << "4. exit\n";
cout << "enter your choice: ";
cin >> choice;
switch(choice)
{
case 1:
cout << "enter element to append: ";
cin >> data;
list.append(data);
break;
case 2:
list.display();
break;
case 3:
list.clear();
break;
case 4:
cout << "exited!" << endl;
break;
default:
cout << "invalid choice" << endl;
}
}
while (choice != 4);
return 0;
}
// Conclusion:
// The code offers an implementation of a circular singly linked list,
// allowing users to append elements to the list, display the
// elements currently in the list, and clear the list. It utilizes
// circular linking to ensure that the last node points back to the
// head, creating a circular structure. The provided menu interface
// makes it easy for users to perform operations on the list.