r/programming • u/svpino • May 08 '15
Five programming problems every Software Engineer should be able to solve in less than 1 hour
https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour
2.5k
Upvotes
1
u/UNWS May 08 '15 edited May 08 '15
Ok so here is how you emulate a stack using just one queue. the invariant is that the queue has items ordered in the same way a stack would release them so that if you just dequeue from the queue continuously you have the top element of the emulated stack comes first then the next and so on. So popping from the emulated stack is as simple as dequeuing from the real queue.
Now for the pushing. you need to keep the queue following the invariant so what you do is you enqueue at the end of the queue normally then dequeue and re-enqueue as many items from the top of the queue as there were originally (before the last enqueue of the new item). So now the element you just enqueued is at the top of the queue / emulated stack and all the other items are behind it.
Lets show with a small demonstration.
push: A
queue: <back> A <front>
push: B
queue: originally B A but after the process we dequeue A and enqueue it again so it now becomes A B
push: C
queue: originally C A B but after dequeuing and en-queuing it becomes A B C
pop: C (just a simple dequeue)
queue: A B
pop: B
queue: A
pop: A
queue: empty
You have just emulated a stack using a queue.
So do I get a cookie :P