Stack Implementation In C


/*THIS IS A PROGRAM IN ‘C’TO PERFORM OPERATIONS ON  STACK REPRESENTED BY AN ARRAY

*/

/*

min1():RETURNS THE MINIMUM VALUE OF STACK

  COMPLEXITY IS:O(1)

stack[]:IT IS AN ARRAY WHICH REPRESENTS THE STACK

minstack[]:IT IS AN ARRAY USED TO STORE THE RECENTLY PUSHED MINIMUM VALUES

*/

#include<cstdio>

#define MAX 100

#include<cstdlib>

struct stack

{

 int top;

 int mtop;

 int stack[MAX]; /*array representation of stack*/

 int minstack[MAX];  /*array to maintain minimum value stack*/

}s,*ptr=&s;

struct stack* push(struct stack* k,int t)

{

 if(k->top>MAX)

  printf(“\nthe stack is overflowing\n”);

 else

 {

  k->stack[(k->top)++]=t;

  if(k->mtop>0)

  {

  if(t<k->minstack[k->mtop-1])

   k->minstack[k->mtop++]=t;

  }

  else

   k->minstack[k->mtop++]=t;

 }

 return k;

}

void display(struct stack* k)

{

 int i;

 for(i=0;i<k->top;i++)

  printf(“%d->”,k->stack[i]);

 printf(“\n”);

}

int pop(struct stack* k)

{

 if(k->top<=0)

 {

  printf(“\nthe stack is underflowing\n”);

  return -1111;

 }

 else

 {

  if(k->minstack[k->mtop-1]==k->stack[k->top-1])

  {

   k->mtop–;

  }

  return k->stack[–(k->top)];

 }

}

int min1(struct stack* k)

{

 if(k->mtop<=0)

  return -1111;

 return k->minstack[(k->mtop)-1];

}

void choice(struct stack* ptr)

{

 int ch,i,t;

while(1)

{

printf(“\nchoose the following operation to be performed\n”);

printf(“1.push\t2.pop\t3.minimum value\t4.display\t5.exit\n”);

scanf(“%d”,&ch);

switch(ch)

{

case 1:

 printf(“enter the data to be pushed\n”);

 scanf(“%d”,&i);

 ptr=push(ptr,i);

 break;

case 2:

 t=pop(ptr);

 if(t!=-1111)

 {

 printf(“the element popped from the stack is  :%d\n”,t);

 }

 break;

case 3:

 t=min1(ptr);

 if(t==-1111)

 {

  printf(“there are no elements in the stack\n”);

 }

 else

  printf(“\nthe minimum value of the stack is %d\n”,t);

 break;

case 4:

 display(ptr);

 break;

case 5:

 exit(1);

default:

 printf(“enter correct choice\n”);

}

}

}

int main()

{

 s.top=0;

 s.mtop=0;

 choice(ptr);

return 0;

}

One thought on “Stack Implementation In C”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s