Sometimes, I come across the following interview question: How to implement 3 stacks with one array ? Of course, any static allocation is not a solution.
Partitioning the array into 3 parts in not a good idea as it will give overflow if there are many elements in stack1
and very few elements in the other two.
My idea:
Keep three pointers ptr1
, ptr2
, ptr3
to point the top element of respective stacks.
Initially ptr1 = ptr2 = ptr3 = -1
;
In the array, the even indexed element will store the value and odd indexed element will store the index of previous element of that stack
.
For example,
s1.push(1);
s2.push(4);
s3.push(3);
s1.push(2);
s3.push(7);
s1.push(10);
s1.push(5);
then our array looks like:
1, -1, 4, -1, 3, -1, 2, 0, 7, 4, 10, 6, 5, 10
and the values of pointers are:
ptr1 = 12, ptr2 = 2 , ptr3 = 8