- Uncategorized

Stack: Data Structure algorithm

stack
Stack is a data structure which has ordered list of similar data type. Stack is a Last In First Out (LIFO) structure. In simple words, stack is a like a bag; whatever you put at last comes out first. Now, lets understand the algorithm for stack.

  • start
  • Display push or pop
  • Read input
  • If push
    • Read input data
    • Check for Stack overflow
    • If flase
      • push data into stack
      • Increment stack top pointer
    • If true 
      • Display “Stack overflow”
      • Stop
  • If pop
    • Check for Stack underflow
    • If false
      • Read stack top data
      • Display stack top data
      • Decrement  stack top pointer
    • if true
      • Display stack underflow
      • Stop
  • Stop
Lets understand this with an example of stack using simple array which stores integer type data.

//Program of Stack using array
//author Sujay K
//@ codesexplorer.blogspot.in
#include
#define size 10
int top=-1;
void push(int *,int );
int pop(int *);
int full();
int empty();
int main()
{
int a[10],c,r;
do
{
printf("n Enter:n 1-> Pushn 2-> Popn 3-> Stack top elementn 0-> exit");
scanf("%d",&c);
switch(c)
{
case 1: printf("n Enter data: ");
scanf("%d",&r);
push(a,r);
break;
case 2: r=pop(a);
printf("n Poped data: %d",r);
break;
case 3: if(full())
printf("n Stack overflow");
else if(empty())
printf("n Stack Underflow");
else
printf("n Stack top element: %d",a[top]);
break;
case 0: break;
default: printf("n You hit a wrong choice, Try again");
}
}while(c!=0);
return 0;
}

void push(int *s, int data)
{
if(!full())
s[++top]=data;
else
printf("n Stack Overflow");
}

int pop(int *s)
{
if(!empty())
return s[top--];
else
{
printf("n Stack underflow");
return -1;
}
return 0;
}

int full()
{
if(top>=size)
return 1;
else
return 0;
}

int empty()
{
if(top<0)
return 1;
else
return 0;
}
   

Hope you understood stack algorithm and program, Try your own using algorithm. We can  implement stack using dynamic memory allocation also. I will explain you about that when we discuss Linked lists. You can download this program by below link.

Leave your comments in comments section, feel free to ask your doubts.
Next post will be of applications of stack.

Sujay K

Leave a Reply