-
Notifications
You must be signed in to change notification settings - Fork 0
/
7singly_LL.cpp
133 lines (115 loc) · 2.8 KB
/
7singly_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
// 7. Implement Singly Linked List ADT.
// Theory:
// This code implements a 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 singlylist 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 singlylist
{
private:
Node* head;
Node* tail;
public:
singlylist()
{
head = nullptr;
tail = nullptr;
}
void append(int value)
{
Node* newNode = new Node(value);
if (head == nullptr)
{
head = tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
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;
while (current != nullptr)
{
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
void clear()
{
while (head != nullptr)
{
Node* temp = head;
head = head->next;
delete temp;
}
tail = nullptr;
cout << "list cleared." << endl;
}
};
int main()
{
singlylist 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 a basic implementation of a singly linked list,
// allowing users to append elements to the list, display the elements
// currently in the list, and clear the list. It provides a
// user-friendly menu interface for interacting with the list, making
// it easy to perform operations on the list.