C++ Program to implement Stacks
Program
#include<iostream>
#include<cstdlib>
#define SIZE 5
int top = -1;
using namespace std;
class stack
{
int st[SIZE];
public:
void push(int);
void pop();
void display();
};
void stack::push(int item)
{
if(top == SIZE - 1)
{
cout << "Stack overflow" << endl;
return;
}
top++;
st[top] = item;
}
void stack::pop()
{
if(top == -1)
{
cout << "Stack underflow" << endl;
return;
}
cout << "Deleted item is:\t" << st[top] << endl;
top--;
}
void stack::display()
{
if(top == -1)
{
cout << "Stack empty. Nothing to display" << endl;
return;
}
cout << "Contents of stack are:" << endl;
for (int i = 0; i < top + 1; i++)
cout << st[i] << endl;
}
int main()
{
int choice, item;
stack st;
while(1)
{
cout << "MENU" << endl;
cout << "1. Push\n2. Pop\n3. Display\n4. Exit" << endl;
cin >> choice;
switch(choice)
{
case 1:
cout << "Enter the item to push" << endl;
cin >> item;
st.push(item);
break;
case 2:
st.pop();
break;
case 3:
st.display();
break;
default:
exit(0);
}
}
return 0;
}
Output
MENU
1. Push
2. Pop
3. Display
4. Exit
2
Stack underflow
MENU
1. Push
2. Pop
3. Display
4. Exit
1
Enter the item to push
10
MENU
1. Push
2. Pop
3. Display
4. Exit
1
Enter the item to push
20
MENU
1. Push
2. Pop
3. Display
4. Exit
1
Enter the item to push
30
MENU
1. Push
2. Pop
3. Display
4. Exit
3
Contents of stack are:
10
20
30
MENU
1. Push
2. Pop
3. Display
4. Exit
2
Deleted item is: 30
MENU
1. Push
2. Pop
3. Display
4. Exit
2
Deleted item is: 20
MENU
1. Push
2. Pop
3. Display
4. Exit
2
Deleted item is: 10
MENU
1. Push
2. Pop
3. Display
4. Exit
2
Stack underflow
MENU
1. Push
2. Pop
3. Display
4. Exit
1
Enter the item to push
40
MENU
1. Push
2. Pop
3. Display
4. Exit
4