-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquestion8.cpp
114 lines (94 loc) · 2.42 KB
/
question8.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
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
class Stack {
private:
Node* top;
public:
Stack() : top(nullptr) {}
~Stack() {
Node* current = top;
while (current != nullptr) {
Node* next = current->next;
delete current;
current = next;
}
}
bool isEmpty() {
return (top == nullptr);
}
void push(int value) {
Node* newNode = new Node(value);
newNode->next = top;
top = newNode;
cout << "Item " << value << " pushed onto the stack." << endl;
}
void pop() {
if (isEmpty()) {
cout << "Stack is empty. Cannot pop." << endl;
} else {
Node* temp = top;
top = top->next;
cout << "Item " << temp->data << " popped from the stack." << endl;
delete temp;
}
}
void display() {
if (isEmpty()) {
cout << "Stack is empty." << endl;
} else {
Node* current = top;
cout << "Stack: ";
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
}
};
int main() {
Stack stack;
int choice, value;
do {
cout << "\nMenu:\n";
cout << "1. isEmpty\n";
cout << "2. Push\n";
cout << "3. Pop\n";
cout << "4. Display\n";
cout << "5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
if (stack.isEmpty()) {
cout << "Stack is empty." << endl;
} else {
cout << "Stack is not empty." << endl;
}
break;
case 2:
cout << "Enter the value to push onto the stack: ";
cin >> value;
stack.push(value);
break;
case 3:
stack.pop();
break;
case 4:
stack.display();
break;
case 5:
cout << "Exiting program.\n";
break;
default:
cout << "Invalid choice. Please enter a valid option.\n";
}
} while (choice != 5);
return 0;
}