Two Queues Make A Stack
November 5, 2013
There are basically two ways to approach the problem, one that is efficient when pushing an element and one that is efficient when popping an element. We’ll call the two queues Q1 and Q2.
Efficient pushing: To push an element, enqueue the new element to Q1. To pop an element, dequeue everything except the last element from Q1 and enqueue the elements on Q2, dequeue the last element from Q2 and save it, swap the two queues, and return the saved element.
Efficient popping: To push an element, enqueue the new element to Q2, dequeue everything from Q2 and enqueue the elements on Q1, and swap the two queues. To pop the stack, dequeue the first element of Q1 and return it.
The isEmpty operation simply checks if both queues are empty. In both cases the time complexity is constant for the efficient operation but the other operation is linear in the number of elements in the stack, because each operation has to touch each element.
I’m sorry, but I don’t have time to write the code. My mother is unwell again, in hospital. First they said she had mild heart failure — I’m not sure how the adjective mild applies in that situation. Then they said the problem was fluid in the lungs, and they gave her a diuretic. Now she is dehydrated and receiving liquids. I’m not sure I understand, but she seems to be doing okay. Anyway, you’ll have to write the code yourselves, based on the outlines given above; will somebody please be sure to write a Scheme solution? Many thanks.
Pages: 1 2