Design a method for keeping two stacks within a single linear array so that neither stack overflows until all of memory is used and an entire stack is never shifted to a different location within the array.
Write usual stack routines to manipulate the two stacks.
Hint : The two stacks grow towards each other. In your function, use an extra integer parameter to identify the stack to be used.
Difficulty level
![](images/star3.png)
Video recording
This exercise is mostly suitable for students
#define N 20
typedef int element;
typedef struct {
element data[N];
int top1,top2;
} stack;
stack CreateStack()
{
stack p;
p.top1 = -1;
p.top2=N;
return p;
}
int Push(stack *p, element e, int n)
{
if (isFullStack(*p)) return 0;
if(n==1)
p->data[++p->top1]=e;
else
p->data[--p->top2] = e;
return 1;
}
int Pop(stack *p, int n)
{
if (isEmptyStack(*p,n)) return 0;
if(n==1)
p->top1--;
else
p->top2++;
return 1;
}
int Top(stack p, element *e, int n)
{
if (isEmptyStack(p,n)) return 0;
if(n==1)
*e = p.data[p.top1];
else
*e = p.data[p.top2];
return 1;
}
int isEmptyStack(stack p, int n)
{
if(n==1)
return (p.top1 == -1);
if(n==2)
return (p.top2==N);
}
int isFullStack(stack p)
{
return (p.top1+1 == p.top2);
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
![](images/star4.png)