---
title: "Linked Lists, Stacks and Queues"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 24
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/24-linked-lists-stacks-and-queues
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 24 — Linked Lists, Stacks and Queues

The undo button of an editor cancels the last change first, then the one before it: the newest change leaves first. A printer serves its waiting documents in the order they came: the oldest leaves first. The two are the same idea, a line of things waiting, taken from opposite ends; and each has a name, an interface, and more than one way to build it.

This chapter separates what a structure does from how it is built. It builds the [linked list](#def-g12-lists-stacks-queues-linked-list), a chain of small [cells](#def-g12-lists-stacks-queues-linked-list), and from it the [stack](#def-g12-lists-stacks-queues-stack) and the [queue](#def-g12-lists-stacks-queues-queue), each in two ways; it counts what each operation costs; and it uses them to check brackets, to compute, and to simulate a day at a post office counter.

**You already know.**

A class groups data with its methods, and an invariant is kept by the methods (chapter [23](https://one-course.com/books/computer-science/2/en/chapter/23-classes-and-objects#ch-g12-classes-and-objects)). A module offers an interface and hides its [implementation](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface) (chapter [20](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#ch-g11-modules-and-interfaces)). The cost of an algorithm (chapter [17](https://one-course.com/books/computer-science/2/en/chapter/17-the-cost-of-an-algorithm#ch-g11-cost-of-an-algorithm)). A dictionary finds a value from its key (Book 1, grade 8).

## 24.1 A structure is defined by its operations

**Definition 24.1 (Abstract data type).**

An *abstract data type* is a kind of data defined only by its operations and what each one does: an interface with its specifications. How the data is stored, its [implementation](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface), is left out; one abstract data type can have several [implementations](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface), and a program that uses only the interface works with any of them.

This is the idea of the module interface, applied to data. The [stack](#def-g12-lists-stacks-queues-stack) and the [queue](#def-g12-lists-stacks-queues-queue) below are [abstract data types](#def-g12-lists-stacks-queues-adt); the [linked list](#def-g12-lists-stacks-queues-linked-list) is one way to implement them.

## 24.2 The linked list

**Definition 24.2 (Linked list, cell).**

A *linked list* is a sequence stored as a chain of *cells*: each cell holds one value and a link to the next cell, and the last cell’s link is `None`. The list is known by its first cell, its head.

```python
"""Linked lists made of cells."""


class Cell:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next                # the next cell, or None at the end


def from_list(values):
    head = None
    for v in reversed(values):          # build from the end: each new cell leads
        head = Cell(v, head)
    return head


def to_list(head):
    out = []
    cell = head
    while cell is not None:
        out.append(cell.value)
        cell = cell.next
    return out
```

***Listing 24.1.** [Cells](#def-g12-lists-stacks-queues-linked-list), and two conversions to and from Python lists. code/grade-12/03-lists-stacks-queues/listings/cell.py*

![The linked list 3, 1, 4, 1. Walking it means following the links from the head; the crossed box is the link None of the last cell. Inserting at the head is one new cell whose link is the old head.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-lists-stacks-queues/fig-e03fb369d473.svg)

*The [linked list](#def-g12-lists-stacks-queues-linked-list) $3, 1, 4, 1$. Walking it means following the links from the head; the crossed box is the link `None` of the last cell. Inserting at the head is one new cell whose link is the old head.*

```python
from cell import Cell, from_list, to_list

head = Cell(3, Cell(1, Cell(4, Cell(1))))   # 3 -> 1 -> 4 -> 1 -> None
cell = head
while cell is not None:                     # walking: follow the links
    print(cell.value, end=" -> ")
    cell = cell.next
print(None)

head = Cell(9, head)                        # insert at the head: one new cell
print(to_list(head))
second = head.next
second.next = second.next.next              # remove the cell after 3: skip it
print(to_list(head))
print(to_list(from_list("abc")), to_list(from_list([])))
```

***Listing 24.2.** Walking, inserting at the head, and removing a cell by skipping it. code/grade-12/03-lists-stacks-queues/listings/linked_demo.py*

```
$ python linked_demo.py
3 -> 1 -> 4 -> 1 -> None
[9, 3, 1, 4, 1]
[9, 3, 4, 1]
['a', 'b', 'c'] []
```

***Output 24.1.** Inserting and removing changed one link each; no value moved.*

A [linked list](#def-g12-lists-stacks-queues-linked-list) and a Python list cost differently. Reading the value at index $i$ of a Python list takes the same short time for every $i$; in a [linked list](#def-g12-lists-stacks-queues-linked-list) it means walking $i$ links. Inserting at the front of a Python list shifts every element by one place; in a [linked list](#def-g12-lists-stacks-queues-linked-list) it is one new cell, whatever the length.

## 24.3 The stack

**Definition 24.3 (Stack, push, pop, LIFO).**

A *stack* is an [abstract data type](#def-g12-lists-stacks-queues-adt) holding a sequence of elements, with four operations: create an empty stack; test whether it is empty; *push* an element on top; *pop* the top element, removing and returning it, which is refused on an empty stack. A fifth, `top`, returns the top without removing it. The last element pushed is the first popped: the stack is *LIFO*, last in, first out.

![A stack before and after one push and one pop. Only the top is reachable; the pop gives back the element of the last push.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-lists-stacks-queues/fig-41e4dba44fb5.svg)

*A [stack](#def-g12-lists-stacks-queues-stack) before and after one [push](#def-g12-lists-stacks-queues-stack) and one [pop](#def-g12-lists-stacks-queues-stack). Only the top is reachable; the [pop](#def-g12-lists-stacks-queues-stack) gives back the element of the last [push](#def-g12-lists-stacks-queues-stack).*

Two [implementations](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface) share one interface. In the first, the top is the end of a Python list; in the second, the top is the head of a [linked list](#def-g12-lists-stacks-queues-linked-list). Both [push](#def-g12-lists-stacks-queues-stack) and [pop](#def-g12-lists-stacks-queues-stack) in a time that does not depend on the number of elements.

```python
"""A stack kept in a Python list: the top is the end of the list."""


class Stack:
    def __init__(self):
        self._items = []

    def is_empty(self):
        return self._items == []

    def push(self, x):
        self._items.append(x)

    def pop(self):
        if self.is_empty():
            raise IndexError("pop from an empty stack")
        return self._items.pop()

    def top(self):
        if self.is_empty():
            raise IndexError("top of an empty stack")
        return self._items[-1]
```

***Listing 24.3.** A [stack](#def-g12-lists-stacks-queues-stack) in a Python list. code/grade-12/03-lists-stacks-queues/listings/stack_list.py*

```python
"""A stack made of linked cells: the top is the first cell."""
from cell import Cell


class Stack:
    def __init__(self):
        self._head = None

    def is_empty(self):
        return self._head is None

    def push(self, x):
        self._head = Cell(x, self._head)

    def pop(self):
        if self.is_empty():
            raise IndexError("pop from an empty stack")
        x = self._head.value
        self._head = self._head.next
        return x

    def top(self):
        if self.is_empty():
            raise IndexError("top of an empty stack")
        return self._head.value
```

***Listing 24.4.** The same interface, with linked [cells](#def-g12-lists-stacks-queues-linked-list). code/grade-12/03-lists-stacks-queues/listings/stack_linked.py*

Since both promise the same behaviour, one [test suite](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-test-suite) checks both: the tests use only the interface, and the class under test is chosen by a loop.

```python
"""One test suite, run on both implementations of the stack."""
import unittest

import stack_linked
import stack_list


class StackTests(unittest.TestCase):
    Stack = None                                # set for each implementation

    def test_new_stack_is_empty(self):
        self.assertTrue(self.Stack().is_empty())

    def test_last_in_first_out(self):
        s = self.Stack()
        for x in [1, 2, 3]:
            s.push(x)
        self.assertEqual([s.pop(), s.pop(), s.pop()], [3, 2, 1])
        self.assertTrue(s.is_empty())

    def test_top_does_not_remove(self):
        s = self.Stack()
        s.push("a")
        self.assertEqual((s.top(), s.top()), ("a", "a"))
        self.assertFalse(s.is_empty())

    def test_empty_stack_refuses(self):
        with self.assertRaises(IndexError):
            self.Stack().pop()
        with self.assertRaises(IndexError):
            self.Stack().top()
```

***Listing 24.5.** One suite of tests for the [stack](#def-g12-lists-stacks-queues-stack) interface. code/grade-12/03-lists-stacks-queues/listings/stacks_tests.py*

```python
for module in [stack_list, stack_linked]:
    suite = unittest.TestSuite()
    for name in unittest.TestLoader().getTestCaseNames(StackTests):
        test = StackTests(name)
        test.Stack = module.Stack
        suite.addTest(test)
    result = unittest.TestResult()
    suite.run(result)
    print(f"{module.__name__:13} {result.testsRun} tests, "
          f"{len(result.failures)} failures, {len(result.errors)} errors")
```

***Listing 24.6.** The suite run on each [implementation](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface) in turn. code/grade-12/03-lists-stacks-queues/listings/stacks_tests.py*

```
$ python stacks_tests.py
stack_list    4 tests, 0 failures, 0 errors
stack_linked  4 tests, 0 failures, 0 errors
```

***Output 24.2.** Both [implementations](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface) pass the four tests.*

## 24.4 The queue

**Definition 24.4 (Queue, enqueue, dequeue, FIFO).**

A *queue* is an [abstract data type](#def-g12-lists-stacks-queues-adt) holding a sequence, with the operations: create an empty queue; test whether it is empty; *enqueue* an element at the back; *dequeue* the element at the front, removing and returning it, refused on an empty queue. The first element enqueued is the first dequeued: the queue is *FIFO*, first in, first out.

A [linked list](#def-g12-lists-stacks-queues-linked-list) makes a [queue](#def-g12-lists-stacks-queues-queue) if the program keeps a second pointer, to the last cell: elements leave at the head and arrive after the tail. Both operations then change one or two links.

![A linked queue holding 5, 8, 2. Enqueueing 7 links a new cell after the tail and moves _tail to it (dashed); dequeueing moves _head to the next cell.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-lists-stacks-queues/fig-96c1d653a599.svg)

*A linked [queue](#def-g12-lists-stacks-queues-queue) holding $5, 8, 2$. Enqueueing $7$ links a new cell after the tail and moves `_tail` to it (dashed); dequeueing moves `_head` to the next cell.*

```python
"""A queue of linked cells, with a pointer to each end."""
from cell import Cell


class Queue:
    def __init__(self):
        self._head = None                   # the first in line: dequeued next
        self._tail = None                   # the last in line
        self.moves = 0                      # cells linked or unlinked

    def is_empty(self):
        return self._head is None

    def enqueue(self, x):
        cell = Cell(x)
        if self.is_empty():
            self._head = cell
        else:
            self._tail.next = cell
        self._tail = cell
        self.moves += 1

    def dequeue(self):
        if self.is_empty():
            raise IndexError("dequeue from an empty queue")
        x = self._head.value
        self._head = self._head.next
        if self._head is None:              # the queue is empty again
            self._tail = None
        self.moves += 1
        return x
```

***Listing 24.7.** A linked [queue](#def-g12-lists-stacks-queues-queue), which also counts its moves. code/grade-12/03-lists-stacks-queues/listings/queue_linked.py*

The second [implementation](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface) surprises: a [queue](#def-g12-lists-stacks-queues-queue) made of two [stacks](#def-g12-lists-stacks-queues-stack). Arrivals are pushed on an [in-stack](#def-g12-lists-stacks-queues-stack). To [dequeue](#def-g12-lists-stacks-queues-queue), the program [pops](#def-g12-lists-stacks-queues-stack) from an [out-stack](#def-g12-lists-stacks-queues-stack); when the [out-stack](#def-g12-lists-stacks-queues-stack) is empty, it first [pops](#def-g12-lists-stacks-queues-stack) every element of the [in-stack](#def-g12-lists-stacks-queues-stack) and [pushes](#def-g12-lists-stacks-queues-stack) it on the [out-stack](#def-g12-lists-stacks-queues-stack), which reverses their order and puts the oldest on top.

![A queue from two stacks. The transfer pops 3, 2, 1 from the in-stack and pushes them on the out-stack, where 1, the oldest, is now on top. The next two dequeues pop 2 and 3 with no transfer.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-lists-stacks-queues/fig-5e57e866ea81.svg)

*A [queue](#def-g12-lists-stacks-queues-queue) from two [stacks](#def-g12-lists-stacks-queues-stack). The transfer [pops](#def-g12-lists-stacks-queues-stack) $3$, $2$, $1$ from the [in-stack](#def-g12-lists-stacks-queues-stack) and [pushes](#def-g12-lists-stacks-queues-stack) them on the [out-stack](#def-g12-lists-stacks-queues-stack), where $1$, the oldest, is now on top. The next two [dequeues](#def-g12-lists-stacks-queues-queue) [pop](#def-g12-lists-stacks-queues-stack) $2$ and $3$ with no transfer.*

```python
"""A queue made of two stacks: arrivals go in, departures come out."""
from stack_linked import Stack


class Queue:
    def __init__(self):
        self._in = Stack()                  # the newest on top
        self._out = Stack()                 # the oldest on top
        self.moves = 0                      # elements placed or removed

    def is_empty(self):
        return self._in.is_empty() and self._out.is_empty()

    def enqueue(self, x):
        self._in.push(x)
        self.moves += 1

    def dequeue(self):
        if self.is_empty():
            raise IndexError("dequeue from an empty queue")
        if self._out.is_empty():            # transfer: reverses the order
            while not self._in.is_empty():
                self._out.push(self._in.pop())
                self.moves += 1
        self.moves += 1
        return self._out.pop()
```

***Listing 24.8.** A [queue](#def-g12-lists-stacks-queues-queue) made of two [stacks](#def-g12-lists-stacks-queues-stack). code/grade-12/03-lists-stacks-queues/listings/queue_two_stacks.py*

One [dequeue](#def-g12-lists-stacks-queues-queue) can be slow: it may transfer every element. But an element is transferred at most once, since it never goes back to the [in-stack](#def-g12-lists-stacks-queues-stack). Counting a “move” each time an element is pushed on the [in-stack](#def-g12-lists-stacks-queues-stack), transferred, or popped from the [out-stack](#def-g12-lists-stacks-queues-stack), each element makes at most three moves in its whole life: $n$ [enqueues](#def-g12-lists-stacks-queues-queue) followed by any [dequeues](#def-g12-lists-stacks-queues-queue) cost at most $3n$ moves in all, however they are interleaved (exercise [24.12](#exo-g12-lists-stacks-queues-12)).

The two [queues](#def-g12-lists-stacks-queues-queue) pass one suite of tests, written like the [stack](#def-g12-lists-stacks-queues-stack) suite; here is one of its four tests.

```python
    def test_mixed_operations(self):
        q, out = self.Queue(), []
        for step in "ab-c--d-":                  # a letter enqueues, - dequeues
            if step == "-":
                out.append(q.dequeue())
            else:
                q.enqueue(step)
        self.assertEqual(out, ["a", "b", "c", "d"])
```

***Listing 24.9.** A test that mixes [enqueues](#def-g12-lists-stacks-queues-queue) and [dequeues](#def-g12-lists-stacks-queues-queue). code/grade-12/03-lists-stacks-queues/listings/queues_tests.py*

```
$ python queues_tests.py
queue_linked     4 tests, 0 failures, 0 errors
queue_two_stacks 4 tests, 0 failures, 0 errors
```

***Output 24.3.** Both [queues](#def-g12-lists-stacks-queues-queue) pass.*

## 24.5 Using them

### Checking brackets

In a program, every opening bracket must be closed by a bracket of the same kind, the last opened being the first closed: a [stack](#def-g12-lists-stacks-queues-stack). Each opening is pushed; each closing must match the top, which is popped; at the end nothing may be left open.

```python
from stack_list import Stack

PAIRS = {")": "(", "]": "[", "}": "{"}


def balanced(text):
    s = Stack()
    for ch in text:
        if ch in "([{":
            s.push(ch)                       # an opening waits for its closing
        elif ch in PAIRS:
            if s.is_empty() or s.pop() != PAIRS[ch]:
                return False                 # nothing open, or the wrong kind
    return s.is_empty()                      # nothing left open


for text in ["f(a[i], {k: (1, 2)})", "(]", "((x)", "x)(", "print('hi')"]:
    print(f"{text:22} {balanced(text)}")
```

***Listing 24.10.** Balanced brackets, with a [stack](#def-g12-lists-stacks-queues-stack). code/grade-12/03-lists-stacks-queues/listings/brackets.py*

```
$ python brackets.py
f(a[i], {k: (1, 2)})   True
(]                     False
((x)                   False
x)(                    False
print('hi')            True
```

***Output 24.4.** `(]` closes the wrong kind; `((x)` leaves one open; `x)(` closes before opening.*

### Computing in postfix notation

**Definition 24.5 (Postfix notation).**

In *postfix notation*, an operator is written after its two operands: $3 + 4$ is `3 4 +`, and $(3 + 4) \times 2$ is `3 4 + 2 *`. No brackets and no priority rules are needed: the order of the operators says everything.

A postfix expression is evaluated with one [stack](#def-g12-lists-stacks-queues-stack): a number is pushed; an operator [pops](#def-g12-lists-stacks-queues-stack) two numbers, the right operand first, and [pushes](#def-g12-lists-stacks-queues-stack) the result. At the end the [stack](#def-g12-lists-stacks-queues-stack) holds exactly one number, the value.

![The stack while 3 4 + 2 * is read, one picture per token. An operator replaces the two numbers on top by its result (shaded); 14 is left alone at the end.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-lists-stacks-queues/fig-ce904ffb1473.svg)

*The [stack](#def-g12-lists-stacks-queues-stack) while `3 4 + 2 *` is read, one picture per token. An operator replaces the two numbers on top by its result (shaded); $14$ is left alone at the end.*

```python
from stack_list import Stack

OPS = {"+": lambda a, b: a + b, "-": lambda a, b: a - b,
       "*": lambda a, b: a * b, "/": lambda a, b: a / b}


def evaluate(expression, show=False):
    s = Stack()
    for token in expression.split():
        if token in OPS:
            b = s.pop()                      # the right operand is on top
            a = s.pop()
            s.push(OPS[token](a, b))
        else:
            s.push(float(token))
        if show:
            print(f"  read {token:>2}   top {s.top()}")
    result = s.pop()
    if not s.is_empty():
        raise ValueError("too many numbers")
    return result


print(evaluate("3 4 + 2 *", show=True))      # (3 + 4) * 2
print(evaluate("3 4 2 * +"))                 # 3 + 4 * 2
print(evaluate("10 2 8 * + 3 -"))            # 10 + 2 * 8 - 3
try:
    evaluate("1 +")
except IndexError as error:
    print("IndexError:", error)
```

***Listing 24.11.** A postfix calculator. code/grade-12/03-lists-stacks-queues/listings/postfix.py*

```
$ python postfix.py
  read  3   top 3.0
  read  4   top 4.0
  read  +   top 7.0
  read  2   top 2.0
  read  *   top 14.0
14.0
11.0
23.0
IndexError: pop from an empty stack
```

***Output 24.5.** The top after each token, then three values and a malformed expression.*

### A waiting line

A counter serves people in the order they came: a [queue](#def-g12-lists-stacks-queues-queue). Here people arrive at random, and the counter serves one every two minutes.

```python
"""Ten minutes at a counter: one person served per two minutes."""
import random

from queue_linked import Queue

rng = random.Random(7)
line, served = Queue(), 0
for minute in range(10):
    arrived = [f"c{minute}{k}" for k in range(rng.randint(0, 2))]
    for person in arrived:
        line.enqueue(person)
    leaving = line.dequeue() if minute % 2 == 1 and not line.is_empty() else "-"
    print(f"minute {minute}: arrive {' '.join(arrived) or '-':8} served {leaving}")
```

***Listing 24.12.** Ten minutes at a counter. code/grade-12/03-lists-stacks-queues/listings/waiting_line.py*

```
$ python waiting_line.py
minute 0: arrive c00      served -
minute 1: arrive -        served c00
minute 2: arrive c20      served -
minute 3: arrive c30 c31  served c20
minute 4: arrive -        served -
minute 5: arrive -        served c30
minute 6: arrive c60 c61  served -
minute 7: arrive -        served c31
minute 8: arrive c80      served -
minute 9: arrive c90 c91  served c60
```

***Output 24.6.** Each person leaves in the order of arrival; `c31` waits four minutes behind `c30`.*

### Choosing a structure

The choice follows from the operations the program needs. Undo, brackets, the calls of a [recursive function](https://one-course.com/books/computer-science/2/en/chapter/22-recursion#def-g12-recursion-recursion): a [stack](#def-g12-lists-stacks-queues-stack). Services in order of arrival, a printer, the visit of a [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) level by level (chapter [26](https://one-course.com/books/computer-science/2/en/chapter/26-graph-traversals-and-shortest-paths#ch-g12-graph-algorithms)): a [queue](#def-g12-lists-stacks-queues-queue). Many insertions at the front: a [linked list](#def-g12-lists-stacks-queues-linked-list). Reading by index: a Python list. Finding a value from a key: a dictionary, which does not scan its keys at all.

```python
"""Looking up a key among n pairs: scanning a list against a dictionary."""
import timeit



def scan(pairs, key):
    for k, v in pairs:
        if k == key:
            return v


for n in [1_000, 10_000, 100_000]:
    pairs = [(f"name{i}", i) for i in range(n)]
    book = dict(pairs)
    key = f"name{n - 1}"                       # the worst case for the scan
    env = {"scan": scan, "pairs": pairs, "book": book, "key": key}
    t_list = min(timeit.repeat("scan(pairs, key)", globals=env, number=20)) / 20
    t_dict = min(timeit.repeat("book[key]", globals=env, number=20_000)) / 20_000
    print(f"n = {n:>7}: list {t_list * 1e6:9.2f} us   dict {t_dict * 1e6:6.3f} us"
          f"   ratio {t_list / t_dict:8.0f}")
```

***Listing 24.13.** Finding a key in a list of pairs and in a dictionary. code/grade-12/03-lists-stacks-queues/listings/list_vs_dict.py*

```
$ python list_vs_dict.py
n =    1000: list     11.01 us   dict  0.013 us   ratio      821
n =   10000: list    104.92 us   dict  0.015 us   ratio     7224
n =  100000: list   1056.88 us   dict  0.012 us   ratio    87679
```

***Output 24.7.** On the author’s laptop: the scan grows ten times with $n$, the dictionary stays at about $0.01$ microseconds.*

## 24.6 Exercises

**Exercise 24.1 ★.**

From an empty [stack](#def-g12-lists-stacks-queues-stack): [push](#def-g12-lists-stacks-queues-stack) $1$, [push](#def-g12-lists-stacks-queues-stack) $2$, [push](#def-g12-lists-stacks-queues-stack) $3$, [pop](#def-g12-lists-stacks-queues-stack), [push](#def-g12-lists-stacks-queues-stack) $4$, [pop](#def-g12-lists-stacks-queues-stack), [pop](#def-g12-lists-stacks-queues-stack). What did the [pops](#def-g12-lists-stacks-queues-stack) return, and what is left?

**Solution of Exercise 24.1.**

The [pops](#def-g12-lists-stacks-queues-stack) return $3$, then $4$, then $2$; the [stack](#def-g12-lists-stacks-queues-stack) holds $1$ alone.

**Exercise 24.2 ★.**

From an empty [queue](#def-g12-lists-stacks-queues-queue): [enqueue](#def-g12-lists-stacks-queues-queue) `a`, `b`, `c`, [dequeue](#def-g12-lists-stacks-queues-queue), [enqueue](#def-g12-lists-stacks-queues-queue) `d`, [dequeue](#def-g12-lists-stacks-queues-queue). What did the [dequeues](#def-g12-lists-stacks-queues-queue) return, and what is left, front first?

**Solution of Exercise 24.2.**

The [dequeues](#def-g12-lists-stacks-queues-queue) return `a`, then `b`; the [queue](#def-g12-lists-stacks-queues-queue) holds `c` then `d`.

**Exercise 24.3 ★.**

Give the [stack](#def-g12-lists-stacks-queues-stack) after each character of `{[()]}(`, and the answer of `balanced`.

**Solution of Exercise 24.3.**

Bottom first: `{`, `{[`, `{[(`, then `{[` after `)`, `{` after `]`, empty after `}`, and `(` after the last character. The string ends with a bracket still open: `False`.

**Exercise 24.4 ★.**

Evaluate `5 1 2 + 4 * + 3 -` by hand, with the [stack](#def-g12-lists-stacks-queues-stack) after each token.

**Solution of Exercise 24.4.**

Bottom first: $[5]$, $[5, 1]$, $[5, 1, 2]$, then `+` gives $[5, 3]$, $[5, 3, 4]$, `*` gives $[5, 12]$, `+` gives $[17]$, $[17, 3]$, and `-` gives $[14]$. The value is $14$, that is $5 + (1 + 2) \times 4 - 3$.

**Exercise 24.5 ★.**

Add a method `size` to both [stacks](#def-g12-lists-stacks-queues-stack). In the linked [stack](#def-g12-lists-stacks-queues-stack), it must not walk the [cells](#def-g12-lists-stacks-queues-linked-list).

**Solution of Exercise 24.5.**

In the list [stack](#def-g12-lists-stacks-queues-stack), `return len(self._items)`. The linked [stack](#def-g12-lists-stacks-queues-stack) keeps a counter: the [constructor](https://one-course.com/books/computer-science/2/en/chapter/23-classes-and-objects#def-g12-classes-and-objects-constructor) sets `self._size = 0`, `push` adds $1$, `pop` subtracts $1$ after a successful [pop](#def-g12-lists-stacks-queues-stack), and `size` returns it. The count is then a second invariant of the class: `_size` is the number of [cells](#def-g12-lists-stacks-queues-linked-list).

**Exercise 24.6 ★★.**

If `pop` did not test for an empty [stack](#def-g12-lists-stacks-queues-stack), what would each [implementation](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface) raise on an empty [stack](#def-g12-lists-stacks-queues-stack)? Why is the test worth writing?

**Solution of Exercise 24.6.**

The list [stack](#def-g12-lists-stacks-queues-stack) would raise `IndexError: pop from empty list`, from Python’s list; the linked [stack](#def-g12-lists-stacks-queues-stack) would raise `AttributeError: 'NoneType' object has no attribute 'value'`, since `_head` is `None`. Two [implementations](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface) of one interface would fail in two different ways, and the second message speaks of the [implementation](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface), not of the [stack](#def-g12-lists-stacks-queues-stack). The test makes both raise the error the interface promises, with a message a user understands.

**Exercise 24.7 ★★.**

Write the length of a [linked list](#def-g12-lists-stacks-queues-linked-list) given by its head, recursively and with a loop.

**Solution of Exercise 24.7.**

    `def length_rec(cell):`

        `return 0 if cell is None else 1 + length_rec(cell.next)`

    `def length_iter(cell):`

        `n = 0`

        `while cell is not None:`

            `n, cell = n + 1, cell.next`

        `return n`

The recursive one needs one frame per cell, and fails beyond Python’s recursion limit (chapter [22](https://one-course.com/books/computer-science/2/en/chapter/22-recursion#ch-g12-recursion)); the loop does not.

**Exercise 24.8 ★★.**

A student’s [queue](#def-g12-lists-stacks-queues-queue) decides that it is empty by `self._tail is None`, and its `dequeue` never changes `_tail`. [Enqueue](#def-g12-lists-stacks-queues-queue) $1$, [dequeue](#def-g12-lists-stacks-queues-queue), [enqueue](#def-g12-lists-stacks-queues-queue) $2$: where is $2$, and what does the next [dequeue](#def-g12-lists-stacks-queues-queue) do?

**Solution of Exercise 24.8.**

After the [dequeue](#def-g12-lists-stacks-queues-queue), `_head` is `None` but `_tail` still points at the cell of $1$. Enqueueing $2$ finds `_tail` not `None`, so it links the new cell after the cell of $1$, which is no longer in the [queue](#def-g12-lists-stacks-queues-queue), and leaves `_head` at `None`. The $2$ is lost: nothing in the [queue](#def-g12-lists-stacks-queues-queue) leads to it. The next [dequeue](#def-g12-lists-stacks-queues-queue) reads `self._head.value` and fails with `AttributeError`. The repair: in `dequeue`, set `_tail` to `None` when `_head` becomes `None`.

**Exercise 24.9 ★★.**

On the [two-stack](#def-g12-lists-stacks-queues-stack) [queue](#def-g12-lists-stacks-queues-queue): [enqueue](#def-g12-lists-stacks-queues-queue) $1$, $2$, $3$, [dequeue](#def-g12-lists-stacks-queues-queue), [enqueue](#def-g12-lists-stacks-queues-queue) $4$, then [dequeue](#def-g12-lists-stacks-queues-queue) three times. Count the moves after each operation.

**Solution of Exercise 24.9.**

[Enqueues](#def-g12-lists-stacks-queues-queue): $1$, $2$, $3$ moves. The first [dequeue](#def-g12-lists-stacks-queues-queue) finds the [out-stack](#def-g12-lists-stacks-queues-stack) empty, transfers $3$ elements ($6$) and [pops](#def-g12-lists-stacks-queues-stack) $1$ ($7$). [Enqueue](#def-g12-lists-stacks-queues-queue) $4$: $8$. [Dequeue](#def-g12-lists-stacks-queues-queue) $2$: $9$; [dequeue](#def-g12-lists-stacks-queues-queue) $3$: $10$. The last [dequeue](#def-g12-lists-stacks-queues-queue) finds the [out-stack](#def-g12-lists-stacks-queues-stack) empty again, transfers $4$ ($11$) and [pops](#def-g12-lists-stacks-queues-stack) it ($12$). Four elements, $12 = 3 \times 4$ moves.

**Exercise 24.10 ★★.**

Write `reverse(head)`, which reverses a [linked list](#def-g12-lists-stacks-queues-linked-list) by changing its links, without creating a cell, and returns the new head.

**Solution of Exercise 24.10.**

    `def reverse(head):`

        `previous = None`

        `while head is not None:`

            `following = head.next`

            `head.next = previous`

            `previous, head = head, following`

        `return previous`

Invariant of the loop: `previous` is the reversed list of the [cells](#def-g12-lists-stacks-queues-linked-list) already visited, and `head` the rest, untouched. One pass, no new cell.

**Exercise 24.11 ★★.**

Write $(2 + 3) \times (7 - 4) / 5$ in [postfix notation](#def-g12-lists-stacks-queues-postfix), and evaluate it with the [stack](#def-g12-lists-stacks-queues-stack) method.

**Solution of Exercise 24.11.**

`2 3 + 7 4 - * 5 /`. The [stack](#def-g12-lists-stacks-queues-stack), bottom first: $[2]$, $[2, 3]$, $[5]$, $[5, 7]$, $[5, 7, 4]$, $[5, 3]$, $[15]$, $[15, 5]$, $[3]$: the value is $3$.

**Exercise 24.12 ★★★.**

Prove that, in the [two-stack](#def-g12-lists-stacks-queues-stack) [queue](#def-g12-lists-stacks-queues-queue), each element makes at most three moves, and deduce that any sequence of operations containing $n$ [enqueues](#def-g12-lists-stacks-queues-queue) makes at most $3n$ moves.

**Solution of Exercise 24.12.**

Follow one element. It is pushed on the [in-stack](#def-g12-lists-stacks-queues-stack) once, by its [enqueue](#def-g12-lists-stacks-queues-queue): one move. Only a transfer takes elements off the [in-stack](#def-g12-lists-stacks-queues-stack), and a transfer puts each one on the [out-stack](#def-g12-lists-stacks-queues-stack): one move. Nothing ever puts an element back on the [in-stack](#def-g12-lists-stacks-queues-stack), so an element is transferred at most once. Only a [dequeue](#def-g12-lists-stacks-queues-queue) takes an element off the [out-stack](#def-g12-lists-stacks-queues-stack), and it leaves the [queue](#def-g12-lists-stacks-queues-queue): one move. So each element makes at most three moves. Every move counted by the class is one of these three, charged to one element; with $n$ elements enqueued, the total is at most $3n$, whatever the order of the operations. A single [dequeue](#def-g12-lists-stacks-queues-queue) may make many moves, but the total stays in proportion to $n$.

**Exercise 24.13 ★★★.**

Write a [queue](#def-g12-lists-stacks-queues-queue) of fixed capacity kept in a Python list of that length, with the index of the oldest element and the number of elements; the indices wrap around to $0$ at the end of the list. A full [queue](#def-g12-lists-stacks-queues-queue) refuses to [enqueue](#def-g12-lists-stacks-queues-queue).

**Solution of Exercise 24.13.**

    `def enqueue(self, x):`

        `if self._count == len(self._slots):`

            `raise OverflowError("the queue is full")`

        `self._slots[(self._first + self._count) % len(self._slots)] = x`

        `self._count += 1`

    `def dequeue(self):`

        `if self._count == 0:`

            `raise IndexError("dequeue from an empty queue")`

        `x = self._slots[self._first]`

        `self._first = (self._first + 1) % len(self._slots)`

        `self._count -= 1`

        `return x`

The [constructor](https://one-course.com/books/computer-science/2/en/chapter/23-classes-and-objects#def-g12-classes-and-objects-constructor) sets `_slots = [None] * capacity`, `_first = 0` and `_count = 0`. The remainder by the capacity makes the index wrap from the last slot to slot $0$; no element ever moves.

**Exercise 24.14 ★★★.**

Write `to_postfix(expression)` for expressions of numbers, `+`, `-`, `*`, `/` and brackets, tokens separated by spaces. Numbers go straight to the output; operators wait on a [stack](#def-g12-lists-stacks-queues-stack), which first gives up the operators of priority greater than or equal to the new one; a closing bracket empties the [stack](#def-g12-lists-stacks-queues-stack) down to its opening bracket.

**Solution of Exercise 24.14.**

    `PRIORITY = {"+": 1, "-": 1, "*": 2, "/": 2}`

    `def to_postfix(expression):`

        `out, ops = [], Stack()`

        `for token in expression.split():`

            `if token in PRIORITY:`

                `while (not ops.is_empty() and ops.top() != "("`

                        `and PRIORITY[ops.top()] >= PRIORITY[token]):`

                    `out.append(ops.pop())`

                `ops.push(token)`

            `elif token == "(":`

                `ops.push(token)`

            `elif token == ")":`

                `while ops.top() != "(":`

                    `out.append(ops.pop())`

                `ops.pop()`

            `else:`

                `out.append(token)`

        `while not ops.is_empty():`

            `out.append(ops.pop())`

        `return " ".join(out)`

“Greater than or equal” makes operators of equal priority leave from the left: `10 - 2 - 3` gives `10 2 - 3 -`, which is $5$, and not $10 - (2 - 3)$. The tests check the expression of exercise [24.11](#exo-g12-lists-stacks-queues-11), and that `1 + 2 * 3 - 8 / 4` evaluates to $5$.

**Exercise 24.15 ★★★.**

Call a string of the characters `(`, `)`, `[`, `]` *balanced* if it is empty, or of the form $(u)v$ or $[u]v$ with $u$ and $v$ balanced. Prove that `balanced` returns `True` exactly on the balanced strings.

**Solution of Exercise 24.15.**

Only the bracket characters count here; other characters do nothing to the [stack](#def-g12-lists-stacks-queues-stack).

*Balanced strings are accepted.* We prove more, by induction on the length: started with any [stack](#def-g12-lists-stacks-queues-stack) $S$, the loop reads a balanced string $w$ without returning `False` and ends with the [stack](#def-g12-lists-stacks-queues-stack) $S$ again. The empty string does nothing. If $w = (u)v$, the `(` is pushed; $u$, shorter, leaves the [stack](#def-g12-lists-stacks-queues-stack) as $S$ with `(` on top; the `)` matches that top and [pops](#def-g12-lists-stacks-queues-stack) it, giving $S$; $v$, shorter, leaves $S$. The same for $[u]v$. Started with an empty [stack](#def-g12-lists-stacks-queues-stack), the function therefore ends with an empty [stack](#def-g12-lists-stacks-queues-stack) and returns `True`.

*Accepted strings are balanced*, by induction on the length. The empty string is balanced. Let $w$ be accepted and not empty. Its first character is an opening bracket, since a closing one would meet an empty [stack](#def-g12-lists-stacks-queues-stack). That bracket lies at the bottom of the [stack](#def-g12-lists-stacks-queues-stack), and is popped at some point, since the [stack](#def-g12-lists-stacks-queues-stack) ends empty: by a closing bracket of the same kind, at some position. Call $u$ the characters strictly between, and $v$ those after. While $u$ is read, the bottom bracket is never reached, so $u$ is read exactly as from an empty [stack](#def-g12-lists-stacks-queues-stack), and ends with the [stack](#def-g12-lists-stacks-queues-stack) holding only that bracket: $u$ is accepted, and balanced by induction. After the matching closing bracket the [stack](#def-g12-lists-stacks-queues-stack) is empty, and $v$ is read from an empty [stack](#def-g12-lists-stacks-queues-stack) and accepted: balanced by induction. So $w = (u)v$ or $[u]v$ is balanced.

## 24.7 Problem: The Queue at the Post Office

**Problem 24.1.**

Weekend problem — a day at the counter

A post office opens for $480$ minutes. In each minute, a customer arrives with chance $0.3$; one clerk serves the line in order, each service taking $1$ to $5$ minutes. At closing time the doors shut and the people inside are still served. The program runs the same day, with the same random numbers, on both [queues](#def-g12-lists-stacks-queues-queue).

```python
"""A day at the post office: 480 minutes of arrivals, one clerk, two queues."""
import random

import queue_linked
import queue_two_stacks


def simulate(Queue, seed=2026):
    rng = random.Random(seed)
    line = Queue()
    waiting = longest_line = longest_wait = customers = 0
    busy_until = 0
    minute = 0
    while minute < 480 or not line.is_empty():   # doors close, the line is served
        if minute < 480 and rng.random() < 0.3:      # an arrival this minute
            line.enqueue(minute)
            customers += 1
            waiting += 1
        if minute >= busy_until and not line.is_empty():
            arrived = line.dequeue()
            waiting -= 1
            longest_wait = max(longest_wait, minute - arrived)
            busy_until = minute + rng.randint(1, 5)  # service of 1 to 5 minutes
        longest_line = max(longest_line, waiting)
        minute += 1
    return customers, longest_line, longest_wait, line.moves


for module in [queue_linked, queue_two_stacks]:
    customers, length, wait, moves = simulate(module.Queue)
    print(f"{module.__name__}: {customers} customers, longest line {length},"
          f" longest wait {wait} min")
    print(f"  moves {moves} = {moves / customers:.2f} per customer")
```

***Listing 24.14.** A day at the post office, on both [queues](#def-g12-lists-stacks-queues-queue). code/grade-12/03-lists-stacks-queues/listings/post_office.py*

```
$ python post_office.py
queue_linked: 114 customers, longest line 5, longest wait 13 min
  moves 228 = 2.00 per customer
queue_two_stacks: 114 customers, longest line 5, longest wait 13 min
  moves 342 = 3.00 per customer
```

***Output 24.8.** One day, two [implementations](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface).*

**Part I — The queue as an abstract data type.**

1. Which operations of the [queue](#def-g12-lists-stacks-queues-queue) does `simulate` use? Which attribute does it read that is not part of the [abstract data type](#def-g12-lists-stacks-queues-adt) ?
2. Why can `simulate` take the class `Queue` as an argument and work with either?
3. What does the [queue](#def-g12-lists-stacks-queues-queue) hold: the customers’ names, or something else? Why is that enough?
4. The variable `waiting` counts the people in line. Why does the program keep it, rather than ask the [queue](#def-g12-lists-stacks-queues-queue) ?

**Part II — Two implementations.**

5. In `queue_linked` , which links change at an [enqueue](#def-g12-lists-stacks-queues-queue) on an empty [queue](#def-g12-lists-stacks-queues-queue) , and on a [queue](#def-g12-lists-stacks-queues-queue) of three?
6. Why must `dequeue` set `_tail` to `None` when the [queue](#def-g12-lists-stacks-queues-queue) becomes empty?
7. In `queue_two_stacks` , when does a [dequeue](#def-g12-lists-stacks-queues-queue) transfer elements, and how many?
8. Give a sequence of $6$ operations in which one [dequeue](#def-g12-lists-stacks-queues-queue) makes $4$ moves.
9. Which [implementation](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface) would you pick for a [queue](#def-g12-lists-stacks-queues-queue) that is mostly empty? For one where every [dequeue](#def-g12-lists-stacks-queues-queue) must be fast?

**Part III — The simulation.**

10. Why is the random generator built from a fixed seed?
11. Why do both [implementations](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface) give exactly the same customers, line and waits?
12. A service lasts $3$ minutes on average over the five durations, and a customer arrives about every $1/0.3 \approx 3.3$ minutes. What happens to the line if the services become a little longer?
13. Why does the loop go on after minute $480$ , and when does it stop?
14. Explain how the program finds each customer’s wait.

**Part IV — Results and costs.**

15. Read the number of customers, the longest line and the longest wait.
16. How many moves does the linked [queue](#def-g12-lists-stacks-queues-queue) make per customer? Why exactly that number?
17. How many does the [two-stack](#def-g12-lists-stacks-queues-stack) [queue](#def-g12-lists-stacks-queues-queue) make per customer? Why exactly $3$ , and not at most $3$ ?
18. Is the [two-stack](#def-g12-lists-stacks-queues-stack) [queue](#def-g12-lists-stacks-queues-queue) slower in time? Compare the work of one move in each.
19. What would change in the moves if the program stopped at minute $480$ , with people still in line?
20. State the result of the day, and of the comparison.

**Solution of Problem 24.1.**

**1.** The [constructor](https://one-course.com/books/computer-science/2/en/chapter/23-classes-and-objects#def-g12-classes-and-objects-constructor), `enqueue`, `dequeue` and `is_empty`. It also reads `moves`, a counter added for this chapter, which is not part of the [queue](#def-g12-lists-stacks-queues-queue)’s interface.

**2.** A class is a value: `simulate` receives it and calls it to build a [queue](#def-g12-lists-stacks-queues-queue). It then uses only the interface, which both classes offer with the same behaviour.

**3.** The minute of each arrival. The only thing the program needs to know about a customer is how long they waited, and that is the minute of service minus the minute of arrival.

**4.** The [abstract data type](#def-g12-lists-stacks-queues-adt) has no operation giving the number of elements. Counting arrivals and departures answers in one step, where walking the [queue](#def-g12-lists-stacks-queues-queue) would cost a step per person.

**5.** On an empty [queue](#def-g12-lists-stacks-queues-queue), no link between [cells](#def-g12-lists-stacks-queues-linked-list): `_head` and `_tail` are both set to the new cell. On a [queue](#def-g12-lists-stacks-queues-queue) of three, the link of the old last cell, and `_tail`.

**6.** With this `enqueue`, which tests emptiness on `_head`, the [queue](#def-g12-lists-stacks-queues-queue) would still work. But `_tail` would keep pointing at a cell that has left the [queue](#def-g12-lists-stacks-queues-queue), so the invariant “`_tail` is `None` exactly when the [queue](#def-g12-lists-stacks-queues-queue) is empty” would be false, and any method relying on it would fail, as in exercise [24.8](#exo-g12-lists-stacks-queues-8).

**7.** When the [out-stack](#def-g12-lists-stacks-queues-stack) is empty. It transfers every element of the [in-stack](#def-g12-lists-stacks-queues-stack).

**8.** [Enqueue](#def-g12-lists-stacks-queues-queue) $1$, $2$, $3$, then [dequeue](#def-g12-lists-stacks-queues-queue) three times. The first [dequeue](#def-g12-lists-stacks-queues-queue) makes $4$ moves: $3$ transfers and one [pop](#def-g12-lists-stacks-queues-stack).

**9.** For both, the linked [queue](#def-g12-lists-stacks-queues-queue): it makes fewer moves, and every operation takes a time that does not depend on the length, where a [dequeue](#def-g12-lists-stacks-queues-queue) of the [two-stack](#def-g12-lists-stacks-queues-stack) [queue](#def-g12-lists-stacks-queues-queue) can transfer the whole line at once.

**10.** So that the run is the same day every time: the output printed in the book is reproduced exactly, and both [implementations](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface) are compared on the same arrivals.

**11.** The [queue](#def-g12-lists-stacks-queues-queue) draws no random numbers, so the generator gives the same numbers in the same order to both runs; and both are [queues](#def-g12-lists-stacks-queues-queue), giving back the same arrival minutes in the same order. Every decision of the program is then the same.

**12.** The clerk is already busy most of the time. If services were longer than the time between arrivals, people would arrive faster than they leave, and the line would grow all day.

**13.** The doors close at minute $480$, but the people inside are served. The loop stops at the first minute from $480$ on at which the line is empty.

**14.** The [queue](#def-g12-lists-stacks-queues-queue) holds each customer’s arrival minute; when one is served, at minute `minute`, the wait is `minute - arrived`, and the longest is kept.

**15.** $114$ customers; at most $5$ people waiting at once; the longest wait $13$ minutes.

**16.** $2$: one [enqueue](#def-g12-lists-stacks-queues-queue) and one [dequeue](#def-g12-lists-stacks-queues-queue) per customer, and all $114$ were served.

**17.** $3$: every customer is enqueued, and, being served, has been transferred once and popped once. The bound of exercise [24.12](#exo-g12-lists-stacks-queues-12) is reached because nobody is left in line.

**18.** A move of either [queue](#def-g12-lists-stacks-queues-queue) creates or unlinks one cell, a few steps of the same kind. The [two-stack](#def-g12-lists-stacks-queues-stack) [queue](#def-g12-lists-stacks-queues-queue) does $342$ moves against $228$: half as much work again, but the same order of cost, in proportion to the number of customers.

**19.** The people still in line would not be dequeued: fewer than $2$ moves per customer for the linked [queue](#def-g12-lists-stacks-queues-queue), fewer than $3$ for the [two-stack](#def-g12-lists-stacks-queues-stack) [queue](#def-g12-lists-stacks-queues-queue), where those still in the [in-stack](#def-g12-lists-stacks-queues-stack) would have made only one.

**20.** **Over the day, $114$ customers, a longest line of $5$ and a longest wait of $13$ minutes, the same with both [queues](#def-g12-lists-stacks-queues-queue); the linked [queue](#def-g12-lists-stacks-queues-queue) makes $228$ moves, $2$ per customer, the [two-stack](#def-g12-lists-stacks-queues-stack) [queue](#def-g12-lists-stacks-queues-queue) $342$, exactly $3$ per customer.**
