-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15stackUsingLinkedList.cpp
More file actions
122 lines (110 loc) · 2.45 KB
/
Copy path15stackUsingLinkedList.cpp
File metadata and controls
122 lines (110 loc) · 2.45 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
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
#include <iostream>
#include <climits>
using namespace std;
class Node {
public:
int a;
Node* next;
Node(int item) {
a = item;
next = NULL;
}
};
class Stack {
Node* head;
public:
Stack() {
head = NULL;
}
bool isEmpty() {
return head == NULL;
}
void push(int item) {
Node* newNode = new Node(item);
if (head == NULL) {
head = newNode;
return;
}
newNode->next = head;
head = newNode;
}
int peek() {
if (head == NULL) {
return INT_MIN;
}
return head->a;
}
int pop() {
if (head == NULL) {
return INT_MIN;
}
Node* temp = head;
head = head->next;
int poppedValue = temp->a;
delete temp;
return poppedValue;
}
void display() {
if (head == NULL) {
cout << "Stack is empty." << endl;
return;
}
Node* temp = head;
while (temp != NULL) {
cout << temp->a << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
Stack s1;
int i = 0;
cout << "To push an integer type 1\n"
<< "To pop an integer type 2\n"
<< "To peek an integer type 3\n"
<< "To display stack type 4\n"
<< "To stop the stack type 5\n";
while (i != 5) {
cin >> i;
switch (i) {
case 1: {
int a;
cout << "Enter a value to push: ";
cin >> a;
s1.push(a);
cout << "Pushed " << a << "\n";
break;
}
case 2: {
int poppedValue = s1.pop();
if (poppedValue == INT_MIN) {
cout << "Stack is empty, nothing to pop!\n";
} else {
cout << "Popped value: " << poppedValue << "\n";
}
break;
}
case 3: {
int topValue = s1.peek();
if (topValue == INT_MIN) {
cout << "Stack is empty!\n";
} else {
cout << "Top value: " << topValue << "\n";
}
break;
}
case 4: {
s1.display();
break;
}
case 5: {
cout << "Exiting...\n";
break;
}
default:
cout << "Input not found, try again.\n";
}
}
return 0;
}