Saturday, 22 December 2012

What is Stack|Example of Stack


By on 01:15

Stack is a data structure or we can say that its a linear data structure which is used to store data element and retrieved data element in LIFO Manner.LIFO stands for Last In First Out.In Stack data element are added,removed from the single end i.e. top of the stack but in queue data element are added,removed from both the ends means insertion from rear end and deletion from front end.In stack we used two terms push and pop.Push means adding element to stack and pop means removing element from stack. 

Let us take an non-programming example:-




In above figure We tried to explain how the stack works in our daily life.Balls are added to the top of the stack.The last ball put in the stack is the first ball removed by the user.




top=4

insert-->push-->top++
delete-->pop-->top--

Functions which are used in Stack:-

1)Push:-Adding element to stack.
2)Pop:-Removing element from stack. 
3)Clear:-Used to clear all the node in the stack.
4)IsEmpty:-Check "Is Stack is Empty".
5)IsFull:-Check "Is Stack is Full".

Programming Example:-Write a Class Stack program which perform this operations:-


1)Push()

2)Pop()
3)Display()

Program:-



#include<iostream.h>

#include<conio.h>
int top=-1;
class stack
{
int st[30];
public:
stack()
{
}
void push(int x)
{
if(top==49)
cout<<"Stack is full";
else 
st[++top]=x;
}
int pop()
{
if(top==-1)
return -999;
else
return st[top--];
}
void display()
{
if(top==-1)
cout<<"Stack is empty";
else
for(int i=0;i<=top;i++)
{
cout<<"\n"<<st[i];
}
}
};

void main()

{
stack object;
int n,ch;
while(1)
{
clrscr();

cout<<"\n Menu\n\1.Push 2.Pop\n 3.Display\n 4. Exit\n Enter your choice";


cin>>ch;

switch(ch)
{
case 1:top==-1;
cout<<"enter a value";
cin>>n;
object.push(x);
break;

case 2:cout<<object.pop();

break;

case 3:object.display();

break;

case 4:Exit(0);

}
}
getch()
}



If you have any query then leave your comments and don't forgot to follow me on Google+,Facebook,Twitter.

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...