Q. Define a method for keeping two stacks within a single linear array S in such a way that neither stack overflows until entire array is used and a whole stack is never shifted to a different location within the array. Write down the routines for pushing and poping elements in two the stacks.
Ans.
/* The Two Stacks Into One Array */
#include
#define MAX 50
int mainarray[MAX];
int top1=-1,top2=MAX;
void push1(int elm)
{
if((top2-top1)==1)
{
clrscr();
printf("\n Array has been Filled !!!");
return;
}
mainarray[++top1]=elm;
}
void push2(int elm)
{
if((top2-top1)==1)
{
clrscr();
printf("\n Array has been Filled !!!");
return;
}
mainarray[--top2]=elm;
}
int pop1()
{
int temp;
if(top1<0)
{
clrscr();
printf(" \n This Stack Is Empty !!!");
return -1;
}
temp=mainarray[top1];
top1--;
return temp;
}
int pop2()
{
int temp;
if(top2>MAX-1)
{
clrscr();
printf(" \n This Stack Is Empty !!!");
return -1;
}
temp=mainarray[top2];
top2++;
return temp;
}