Tuesday, October 16, 2012

Stack implementation using C++

stack example

First of all,what is stack? A stack is a data structure in which addition of new element or deletion of existing element always takes place at the same end. The end is often known as Top of Stack. For example a no. of books kept one above another, if we have to keep a new book there, we will kept it above all the books and suppose we have to take out a book at first we will pick the book which is at the top.






                                                                                                                                                

Click here to download the code


/* Stack Program*/


#include<iostream.h>

#include<conio.h>

#define MAX 10
class stack
{

int top;
public:
int a[MAX];
stack()
{
top=-1;
}
void push(int x);
int pop();
void isEmpty();
void display();
};
void stack::push(int x)
{

if(top>=MAX)
cout<<"stack overflow";
else
{
a[++top]=x;
cout<<"Inserted";
}
}
int stack::pop()
{
if(top<0)
{
cout<<"stack underflow";
return 0;
}
else
{
int d=a[--top];
return d;
}
}
void stack::display()
{
for(int i=0;i<=top;i++)
{
cout<<"\n"<<a[i];
}
}
void stack::isEmpty()
{
if(top<0)
cout<<"Stack empty";
else
cout<<"Stack not empty";
}
void main()
{
stack s;
int x,ch,i;
while(ch!=5)
{
clrscr();
cout<<"\n"<<"Enter Your choice:";
cout<<"\n1. To Push an element";
cout<<"\n2. To Pop an element";
cout<<"\n3. To check if stack is empty";
cout<<"\n4. To display all\n";
cin>>ch;
switch (ch)
{
case 1:
cout<<"\nEnter element";
cin>>x;
s.push(x);
s.display();
getch();
break;
case 2:
i=s.pop();
cout<<"deleted"<<i;
getch();
break;
case 3:
s.isEmpty();
getch();
break;
case 4:
s.display();
getch();
break;
}
}
}





No comments: