Consider a queue data structure, where the two operations of interest are enqueue (at the back of the queue) and dequeue (from the front of the queue). A queue is thus a FIFO (first in-first out) structure. Suppose we implement a queue by using two stacks, A and B, which support operations of push and pop, as follows:
enqueue(x): push x onto stack A
dequeue: if B is not empty return x = pop B
if B is empty
repeat until A is empty
x = pop A
push x onto stack B
return x = pop B
a) This implementation seems to correctly emulate a queue. Illustrate (by drawing the two stacks) how it works for the following sequence of enqueue and dequeue operations:
enqueue 5
enqueue 7
dequeue
enqueue 3
enqueue 6
enqueue 9
dequeue
dequeue
dequeue
dequeue
b) The actual cost of a push or a pop operation is1. What is the worst-case single operation possible after a sequence of n enqueue and dequeue operations, and what is its cost?
c) Explain how a simplistic worst-case analysis would lead to the conclusion that this algorithm would be O(n2).
d) Using the accounting method, assign the lowest (integer) amortized cost possible to the enqueue operation and to the dequeue operation so that after any sequence of n1 enqueues and n2 dequeues, n1?n2, the amortized cost is ? the actual cost. Explain why this works.
e) Show that the total amortized cost, which is an upper bound for the actual cost, over a sequence of n operations is O(n).