<br>
Multiple stack implementation using single array:
We can implement two stacks in a single array. While inserting elements in either stack compare TOP
of each other. (TOP1 pointer for stackl and TOP2 pointer for stack2)
Both stacks use the same array for storing elements.
Two PUSH functions and two POPfunctions.
This is for utilizing memory space.
Both stack grow or shrink in opposite direction.
The first element in stack1 is pushed at index o. The stack2 starts from rightmost corner, the first
element in stack2 is pushed at index MAX=1
USH operation
6 6 85 top2
5 5
4 4 4 insertion
3 3
2 2
1 1
0
15 top1 15 top1
Intially both Stacks are empty PUSH item onto stack2
PUSH item onto stackl
top1=top2=1 topi-top1+1 top2-MAX-1
85 6 85 6
124 5 124 5
100 4etop2 100 4
3 92 3 top2
top2=top1+1 or topl=top2-1 (stack full)
2 25 2
-top1,
1
S
56 top1 56 top2 is decremented for each PUSH operatioi
15 15 top1 is incremented for each PUSH operation
-
:08/909
POP operation:
200 200 top2
5 100 5 top2 5
4 4
3 3 3
106 2 top1 106 2. top1
1 1
12 12 1
91 91
Intially both stacks are empty POP element from stack2
top1=top2=-1 top2=top2+1
top2 is incremented for each POP operation
topl is decremented for each POP operation
<br>
//push function for stack1 I/push function for stack2
void push1int item) void push2(int item)
{ {
if(topl==top2-1) if(top2==top1+1)
printf("\nstack is full"); printf("\nstack is full"):
else else
{
top1++; top2--;
s[topl]=item; s[top2]=item;
I/pop function for stack1 I/pop function for stack2
oid popl0 void popz()
{
int item; int item;
if(topl==-1) if(top2=z-1)
printf("\nStacki is empty:"): printf("\nStack2 is empty:"):
e'se else
{
item=s[top1): item=s[top2];
topl-: top2++;
printf(nDeleted Element from stack1 is %d",item); printf("\nDeleted Element from stack2 is %d",item);