Skip to study material
← Question index

QUESTION 22

Compare stacks and queues and explain a queue implemented using two stacks.

5 marks

Answer in brief

Stacks implement LIFO while ordinary queues implement FIFO.

Example

After inserting 10, 20 and 30, a stack pop returns 30 and a queue dequeue returns 10. Stack operations use top. Queue insertion uses rear and removal uses front. Neither rule requires numerical sorting.

Applications

Undo and nested expression processing fit stacks. Arrival-order jobs and BFS fit queues. Either ADT may use arrays or linked nodes; the access rule does not depend on one memory layout.

Two-stack queue

  1. Keep an input stack and an output stack.
  2. Enqueue pushes onto the input stack.
  3. For dequeue, if output is empty, transfer every input item to output by repeated pop/push.
  4. Pop output; if both are empty, report underflow.

Why it works

The transfer reverses input order so the earliest remaining item reaches output’s top. Keep using output until it empties before another transfer. Moving input on every dequeue regardless of output state would not follow this algorithm.

Complexity

One dequeue can require O(n) transfer work. Across a sequence of operations, each item moves from input to output at most once and is then removed, giving O(1) amortised stack-operation work per queue operation. This is not a claim that every individual dequeue is worst-case constant. The stored items need O(n) space, and bounded stacks still need a capacity policy.

Reference table

↔ Scroll horizontally on a small screen
Stack and queue
FeatureStackOrdinary queue
RuleLIFOFIFO
InsertTopRear
RemoveTopFront
ExampleUndoArrival-order service

Related exam questions

The following are topic matches from the supplied papers. Marks are their printed allocations, separate from the practice answer badge.

  • April/May 2023 · Q1(b) · 3 marks

    How can a queue be constructed using stacks?

    Paper DS01 · page 1
  • September 2021 · Q1(b) · 7 marks

    Differentiate stack and queue.

    Paper DS07 · page 1

View all matching source questions →