Hi
Iam trying to make a queue only by using one stack, but i really cannot figure out how to. I don't know if that could be done without using any temporary place in memory
Thanks
Printable View
Hi
Iam trying to make a queue only by using one stack, but i really cannot figure out how to. I don't know if that could be done without using any temporary place in memory
Thanks
I may be wrong, but I don't think it is possible to implement a queue using only one stack (and a small fixed number of helper variables). The problem is that you cannot access the first element pushed into the stack without popping all the other elements, but if you have no place to hold them, then you cannot pop them off the stack without losing them. (Note that I am assuming that you don't "cheat" by making use of the internals of the stack, e.g., by treating it as an array because it was implemented using an array).Quote:
Originally Posted by antros48
Well you could try something using recursion and the program stack to save each element.
Something like
Code:int pop_front ( &mystack ) {
int temp = pop()
if ( empty ) {
result = temp
} else {
result = pop_front(mystack)
push(temp)
}
return result
}