C++ program for Stack
Stack
A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle.![]() In the stacks only two operations are allowed:
Push adds an item to the top of the stack, Pop removes the item from the top. A helpful analogy is to think of a stack of books; you can remove only the top book, also you can add a new book on the top. Program:
#include<iostream>
#include<stdlib.h>
using namespace std;
int siz,del;
void push(int stack[],int n,int &top)
{
if(top==siz)
{
cout<<"Overflow ";
exit(0); }
else
{
top++;
stack[top]=n;
}
}
void pop(int stack[],int &top)
{
if(top==0)
{
cout<<"Underflow";
exit(0);}
else
{
del=stack[top];
top--;
}
}
void display(int stack[],int top)
{for(int i=top;i>=1;i--)
cout<<"\n"<<stack[i];
}
main()
{ cout<<"Enter size of STACK";
cin>>siz;
int top=0,val,flag,c;
char ch;
int stack[siz];
do{
cout<<"Enter the value to create stack ";
cin>>val;
push(stack,val,top);
cout<<"The stack is ";
display(stack,top);
cout<<"\nWant to insert more ";
cin>>ch;
}while(ch=='y'||ch=='Y');
cout<<"Enter your choice \n1.Push \n2.Pop \nChoice: ";
cin>>c;
switch(c)
{
case 1:do{
cout<<"-----Inserting element ----- \nEnter the value for insertion ";
cin>>val;
push(stack,val,top);
cout<<"The stack is ";
display(stack,top);
cout<<"\nWant to insert more ";
cin>>ch;
}while(ch=='y'||ch=='Y');
break;
case 2:
cout<<"\n-------Deleting top element------ ";
do{
pop(stack,top);
cout<<"\n\nDeleted element is "<<del;
cout<<"\nThe stack is ";
display(stack,top);
cout<<"\nWant to delete more ";
cin>>ch;
}while(ch=='y'||ch=='Y');
break;}
}
Output of the program:
|


Comments
Post a Comment