Sequences for Stacks and Queues

Choose the operations your sequence needs most often, since front and back operations can have different costs.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace stack and queue order
  2. Use a two-ended structure when appropriate
  3. Simulate three enqueues with an intervening dequeue
  4. Choose a representation that keeps removing inexpensive

Trace stack and queue order

With submissions A then B, a stack removes B first and a queue removes A first. Python lists conveniently support appending and popping at the right end. Removing from the front shifts the following elements, as illustrated by list insertion and extension.

Use a two-ended structure when appropriate

Python's deque supports efficient additions and removals at the ends. A waiting list can append on the right and remove from the left. Verify the direction using sample inputs and outputs with at least two distinct entries.[1]

Simulate three enqueues with an intervening dequeue

Start empty, enqueue red and blue, then dequeue and return red. Enqueue green. The remaining dequeue order is blue, then green. Treat enqueue and dequeue names as part of the interface so callers need not inspect the underlying sequence. Dequeuing from an empty queue needs a documented error, sentinel or wait operation. In a work scheduler, preserving a received order can matter even when the work items have equal priority. See sequences of events.

Choose a representation that keeps removing inexpensive

With a Python list, repeatedly removing position zero shifts the remaining entries. Draining \(n\) entries this way can move roughly \(n(n-1)/2\) references. A deque supports removals at its ends without shifting the full suffix. A list with a separate head index also avoids shifts on each operation, but should eventually release discarded entries. Test that the order remains correct after both filling and draining several times. See counting primitive operations.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩