এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
High School Computer Science · শ্রেণি 10–12
24Linked 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, a chain of small cells, and from it the stack and the 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). A module offers an interface and hides its implementation (chapter 20). The cost of an algorithm (chapter 17). 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, is left out; one abstract data type can have several implementations, 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 and the queue below are abstract data types; the 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.
"""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
None of the last cell. Inserting at the head is one new cell whose link is the old head.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([])))
$ python linked_demo.py
3 -> 1 -> 4 -> 1 -> None
[9, 3, 1, 4, 1]
[9, 3, 4, 1]
['a', 'b', 'c'] []
A linked list and a Python list cost differently. Reading the value at index of a Python list takes the same short time for every ; in a linked list it means walking links. Inserting at the front of a Python list shifts every element by one place; in a 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 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.
Two implementations 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. Both push and pop in a time that does not depend on the number of elements.
"""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]
"""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
Since both promise the same behaviour, one test suite checks both: the tests use only the interface, and the class under test is chosen by a loop.
"""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()
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")
$ python stacks_tests.py
stack_list 4 tests, 0 failures, 0 errors
stack_linked 4 tests, 0 failures, 0 errors
24.4 The queue
Definition 24.4 (Queue, enqueue, dequeue, FIFO)
A queue is an abstract data type 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 makes a 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.
_tail to it (dashed); dequeueing moves _head to the next cell."""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
The second implementation surprises: a queue made of two stacks. Arrivals are pushed on an in-stack. To dequeue, the program pops from an out-stack; when the out-stack is empty, it first pops every element of the in-stack and pushes it on the out-stack, which reverses their order and puts the oldest on top.
"""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()
One dequeue 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. Counting a “move” each time an element is pushed on the in-stack, transferred, or popped from the out-stack, each element makes at most three moves in its whole life: enqueues followed by any dequeues cost at most moves in all, however they are interleaved (exercise 24.12).
The two queues pass one suite of tests, written like the stack suite; here is one of its four tests.
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"])
$ python queues_tests.py
queue_linked 4 tests, 0 failures, 0 errors
queue_two_stacks 4 tests, 0 failures, 0 errors
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. Each opening is pushed; each closing must match the top, which is popped; at the end nothing may be left open.
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)}")
$ python brackets.py
f(a[i], {k: (1, 2)}) True
(] False
((x) False
x)( False
print('hi') True
(] 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: is 3 4 +, and 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: a number is pushed; an operator pops two numbers, the right operand first, and pushes the result. At the end the stack holds exactly one number, the value.
3 4 + 2 * is read, one picture per token. An operator replaces the two numbers on top by its result (shaded); is left alone at the end.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)
$ 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
A waiting line
A counter serves people in the order they came: a queue. Here people arrive at random, and the counter serves one every two minutes.
"""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}")
$ 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
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: a stack. Services in order of arrival, a printer, the visit of a graph level by level (chapter 26): a queue. Many insertions at the front: a linked list. Reading by index: a Python list. Finding a value from a key: a dictionary, which does not scan its keys at all.
"""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}")
$ 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
24.6 Exercises
Exercise 24.1 ★
From an empty stack: push , push , push , pop, push , pop, pop. What did the pops return, and what is left?
Exercise 24.2 ★
From an empty queue: enqueue a, b, c, dequeue, enqueue d, dequeue. What did the dequeues return, and what is left, front first?
Exercise 24.3 ★
Give the stack after each character of {[()]}(, and the answer of balanced.
Solution
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 after each token.
Solution
Solution of Exercise 24.4.
Bottom first: , , , then + gives , , * gives , + gives , , and - gives . The value is , that is .
Exercise 24.5 ★
Add a method size to both stacks. In the linked stack, it must not walk the cells.
Solution
Solution of Exercise 24.5.
In the list stack, return len(self._items). The linked stack keeps a counter: the constructor sets self._size = 0, push adds , pop subtracts after a successful pop, and size returns it. The count is then a second invariant of the class: _size is the number of cells.
Exercise 24.6 ★★
If pop did not test for an empty stack, what would each implementation raise on an empty stack? Why is the test worth writing?
Solution
Solution of Exercise 24.6.
The list stack would raise IndexError: pop from empty list, from Python’s list; the linked stack would raise AttributeError: 'NoneType' object has no attribute 'value', since _head is None. Two implementations of one interface would fail in two different ways, and the second message speaks of the implementation, not of the 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 given by its head, recursively and with a loop.
Solution
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); the loop does not.
Exercise 24.8 ★★
A student’s queue decides that it is empty by self._tail is None, and its dequeue never changes _tail. Enqueue , dequeue, enqueue : where is , and what does the next dequeue do?
Solution
Solution of Exercise 24.8.
After the dequeue, _head is None but _tail still points at the cell of . Enqueueing finds _tail not None, so it links the new cell after the cell of , which is no longer in the queue, and leaves _head at None. The is lost: nothing in the queue leads to it. The next dequeue 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 queue: enqueue , , , dequeue, enqueue , then dequeue three times. Count the moves after each operation.
Exercise 24.10 ★★
Write reverse(head), which reverses a linked list by changing its links, without creating a cell, and returns the new head.
Solution
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 already visited, and head the rest, untouched. One pass, no new cell.
Exercise 24.11 ★★
Write in postfix notation, and evaluate it with the stack method.
Solution
Solution of Exercise 24.11.
2 3 + 7 4 - * 5 /. The stack, bottom first: , , , , , , , , : the value is .
Exercise 24.12 ★★★
Prove that, in the two-stack queue, each element makes at most three moves, and deduce that any sequence of operations containing enqueues makes at most moves.
Solution
Solution of Exercise 24.12.
Follow one element. It is pushed on the in-stack once, by its enqueue: one move. Only a transfer takes elements off the in-stack, and a transfer puts each one on the out-stack: one move. Nothing ever puts an element back on the in-stack, so an element is transferred at most once. Only a dequeue takes an element off the out-stack, and it leaves the 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 elements enqueued, the total is at most , whatever the order of the operations. A single dequeue may make many moves, but the total stays in proportion to .
Exercise 24.13 ★★★
Write a 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 at the end of the list. A full queue refuses to enqueue.
Solution
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 sets _slots = [None] * capacity, _first = 0 and _count = 0. The remainder by the capacity makes the index wrap from the last slot to slot ; 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, which first gives up the operators of priority greater than or equal to the new one; a closing bracket empties the stack down to its opening bracket.
Solution
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 , and not . The tests check the expression of exercise 24.11, and that 1 + 2 * 3 - 8 / 4 evaluates to .
Exercise 24.15 ★★★
Call a string of the characters (, ), [, ] balanced if it is empty, or of the form or with and balanced. Prove that balanced returns True exactly on the balanced strings.
Solution
Solution of Exercise 24.15.
Only the bracket characters count here; other characters do nothing to the stack.
Balanced strings are accepted. We prove more, by induction on the length: started with any stack , the loop reads a balanced string without returning False and ends with the stack again. The empty string does nothing. If , the ( is pushed; , shorter, leaves the stack as with ( on top; the ) matches that top and pops it, giving ; , shorter, leaves . The same for . Started with an empty stack, the function therefore ends with an empty stack and returns True.
Accepted strings are balanced, by induction on the length. The empty string is balanced. Let be accepted and not empty. Its first character is an opening bracket, since a closing one would meet an empty stack. That bracket lies at the bottom of the stack, and is popped at some point, since the stack ends empty: by a closing bracket of the same kind, at some position. Call the characters strictly between, and those after. While is read, the bottom bracket is never reached, so is read exactly as from an empty stack, and ends with the stack holding only that bracket: is accepted, and balanced by induction. After the matching closing bracket the stack is empty, and is read from an empty stack and accepted: balanced by induction. So or 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 minutes. In each minute, a customer arrives with chance ; one clerk serves the line in order, each service taking to 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.
"""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")
$ 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
Part I — The queue as an abstract data type.
- Which operations of the queue does
simulateuse? Which attribute does it read that is not part of the abstract data type? - Why can
simulatetake the classQueueas an argument and work with either? - What does the queue hold: the customers’ names, or something else? Why is that enough?
- The variable
waitingcounts the people in line. Why does the program keep it, rather than ask the queue?
Part II — Two implementations.
- In
queue_linked, which links change at an enqueue on an empty queue, and on a queue of three? - Why must
dequeueset_tailtoNonewhen the queue becomes empty? - In
queue_two_stacks, when does a dequeue transfer elements, and how many? - Give a sequence of operations in which one dequeue makes moves.
- Which implementation would you pick for a queue that is mostly empty? For one where every dequeue must be fast?
Part III — The simulation.
- Why is the random generator built from a fixed seed?
- Why do both implementations give exactly the same customers, line and waits?
- A service lasts minutes on average over the five durations, and a customer arrives about every minutes. What happens to the line if the services become a little longer?
- Why does the loop go on after minute , and when does it stop?
- Explain how the program finds each customer’s wait.
Part IV — Results and costs.
- Read the number of customers, the longest line and the longest wait.
- How many moves does the linked queue make per customer? Why exactly that number?
- How many does the two-stack queue make per customer? Why exactly , and not at most ?
- Is the two-stack queue slower in time? Compare the work of one move in each.
- What would change in the moves if the program stopped at minute , with people still in line?
- State the result of the day, and of the comparison.
Solution
Solution of Problem 24.1.
1. The constructor, enqueue, dequeue and is_empty. It also reads moves, a counter added for this chapter, which is not part of the queue’s interface.
2. A class is a value: simulate receives it and calls it to build a 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 has no operation giving the number of elements. Counting arrivals and departures answers in one step, where walking the queue would cost a step per person.
5. On an empty queue, no link between cells: _head and _tail are both set to the new cell. On a queue of three, the link of the old last cell, and _tail.
6. With this enqueue, which tests emptiness on _head, the queue would still work. But _tail would keep pointing at a cell that has left the queue, so the invariant “_tail is None exactly when the queue is empty” would be false, and any method relying on it would fail, as in exercise 24.8.
7. When the out-stack is empty. It transfers every element of the in-stack.
8. Enqueue , , , then dequeue three times. The first dequeue makes moves: transfers and one pop.
9. For both, the linked queue: it makes fewer moves, and every operation takes a time that does not depend on the length, where a dequeue of the two-stack 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 are compared on the same arrivals.
11. The queue draws no random numbers, so the generator gives the same numbers in the same order to both runs; and both are queues, 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 , but the people inside are served. The loop stops at the first minute from on at which the line is empty.
14. The 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. customers; at most people waiting at once; the longest wait minutes.
16. : one enqueue and one dequeue per customer, and all were served.
17. : every customer is enqueued, and, being served, has been transferred once and popped once. The bound of exercise 24.12 is reached because nobody is left in line.
18. A move of either queue creates or unlinks one cell, a few steps of the same kind. The two-stack queue does moves against : 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 moves per customer for the linked queue, fewer than for the two-stack queue, where those still in the in-stack would have made only one.
20. Over the day, customers, a longest line of and a longest wait of minutes, the same with both queues; the linked queue makes moves, per customer, the two-stack queue , exactly per customer.