Multiple Stacks in an array
Program for representing multiple stacks in one array
/*Implementing multiple stacks in a single array*/
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define MAX 10
void push(int,int[],int,int);
int pop(int,int[],int);
void display(int,int[],int);
/*array to top index for each stack*/
int t[MAX];
int top[MAX];
void main()
{
int arr[MAX],n,totstk,index;
int i,j,k=0,span,no,ch,num;
/*Input total elements of the array*/
/*This array may be divided into multiple stacks*/
printf(“nEnter size of the array?”);
scanf(“%d”,&n);
/*Input total stacks to be created in above array*/
printf(“nEnter total stacks to create?”);
scanf(“%d”,&totstk);
/*t[] array will contains totstk indexes for top*/
/*since total stacks to be created are totstk*/
/*Initializing t[] array with -1*/
for(i=0;i<totstk;i++)
t[i]=-1;
/*computes size of one stack*/
span=n/totstk;
/*store top of each stack in the array*/
/*this top serves as index for push/pop operations*/
top[k++]=0;
for(i=0;i<totstk-1;i++,k++)
top[k]=top[k-1]+span;
/*displaying elements of indexed array*/
for(i=0;i<totstk;i++)
printf(“%dt”,top[i]);
do{
clrscr();
printf(“nStacks-Menu (n stacks:1 array)”);
printf(“n1. Push”);
printf(“n2. Pop”);
printf(“n3. Display”);
printf(“n4. Quit”);
printf(“nnEnter your choice?”);
scanf(“%d”,&ch);
if(ch!=4)
{
printf(“nEnter stack number (0 to %d)?”,totstk-1);
scanf(“%d”,&index);
}
switch(ch)
{
case 1:
printf(“nEnter number to push?”);
scanf(“%d”,&no);
push(index,arr,span,no);
break;
case 2:
num=pop(index,arr,span);
printf(“nPopped element from stack %d is %d”,index,num);
break;
case 3:
display(index,arr,span);
break;
case 4:
exit(0);
}
getch();
}while(1);
}
void push(int index,int arr[],int n,int num)
{
int topid,topelement;
topid=top[index];
topelement=t[index];
if(topelement==topid+n-1)
{printf(“nStack Full! Overflow.”);
return;
}
topelement=++t[index];
arr[topid+topelement]=num;
}
int pop(int index,int arr[],int n)
{
int topid,topelement;
topid=top[index];
topelement=t[index];
if(topelement==-1)
{printf(“nStack Empty! Underflow.”);
return -1;
}
t[index]–;
return(arr[topid+topelement]);
}
void display(int index,int arr[],int n)
{
int i,topid,topelement;
topid=top[index];
topelement=t[index];
if(topelement==-1)
{printf(“nStack Empty! Underflow.”);
return;
}
for(i=topid+topelement;i>=topid;i–)
printf(“%dt”,arr[i]);
}