I implemented it as an array with two stacks adjacent to each other, but their tops on the either ends. That is, if top(stack1) is at the beginning of keys, top(stack2) is at the end of keys. Bottom(Stack1) and Bottom(Stack2) should be adjacent, but anywhere between top(Stack1) and top(Stack2). To delete, I am poping from Top(Stack1), and for inserting, I am pushing in Top(stack2). Could somebody pls tell me if it is correct to do it this way?
When I read CLRS, I solved the que this way, and had no way to know that it was ryt or not. But it was asked in today’s exam, and everyone later on was discussing the way given officially (here and everywhere else on net), so it seems I am the only one to do it such a way. I really wanna know if this is wrong or right ? Please help
Queues and stacks are abstract data structures which have well defined behaviors and any implementation of these data structures should respect this contract.
Your idea of using a single array to implement two stacks is good. But, the inserts and deletes should happen on both stacks.
For eg. lets say you have this setup
2 3 4 5 6top(stack1) is
2bottom(stack1) is
4top(stack2) is
6bottom(stack2) is
5after popping from stack1 3 times you would have reached the bottom of your stack i.e
4and no longer able to pop anything even though there are two more elements in yourQUEUEimplementation. So, a few corrections to your implementation is required.So, if I were to implement two stacks which emulate a QUEUE, this is how I would do it.
Stack1:
2 3 4 5 6which is essentially an array2is the bottom of the stack and6is the top of the stack.Stack2:
emptyInsert an element to Queue:
This is very simple. Just add to the end of array i.e stack1
stack1:
2 3 4 5 6 7Now
7is the top of the stack.Delete an element from Queue:
1. Pop all elements in stack1 and insert them to stack2. So, your array will be reversed
stack1:
emptystack2:
7 6 5 4 3 2. Now2is at the top of the stack.2. Now your top(stack2) will be pointing to
2. Just pop it.7 6 5 4 33. Now for the remaining elements in stack2, pop from stack2 and insert them to stack1.
stack2:
emptystack1:
3 4 5 6 7PS: The above algorithm assumes that you know how to manage memory for arrays as it shrinks or expands.