Concept
Stack is a data structure which operates on LIFO(last in first out) principle.The element that we push in last,pops out first.Here's an example
![Stack Stack-data-structure](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi27is9rdAhWBv_fl2HgGSrjMYvcTwCJ1DekSzdv2PRj31sptl5z6OIy15AuUHr87nBhfVeNOHB4cK6j72gyTSc7wRSrOIopDbRYqlqxo6wD7lXpFgr5YOftUd3lpmYDIHJTcGnnX7Z2lw/s640/st.png)
Top keeps track of the top element of the stack.
Lets see how we can implement a stack using an array.
Lets see how we can implement a stack using an array.
Declaring the stack structure
typedef struct
{
int top,arr[15];
}stack;
Declare stack variable
stack s;
Initialize
s.top = -1
Check empty stack
s.top == -1
Push
top is incremented and new element is pushed in at that position.
void push()
{
int element;
do
{
if(s.top==(SIZE-1))
{
printf("Stack full");
break;
}
printf("Enter element to be pushed ");
scanf("%d",&element);
s.arr[++s.top] = element;
printf("Push more elements ? ");
fflush(stdin);
}while(getchar()=='y');
}
Pop
the top element is returned from the stack and top is decremented.
int pop()
{
if(isEmpty())
{
printf("Stack is empty.Can't pop.");
return -1;
}
return s.arr[s.top--];
}
No comments:
Post a Comment