Volume C2 · Information structures · TAOCP Section 2.2.1
Stacks, queues and deques
Draft. This chapter is written and checked by the tools of the project, and a person has not reviewed it yet. Read it with care.
Read it next to Section 2.2.1 of the book. Study the section: what to read first and the exercises, easiest first. The items of the section and their status.
Read first
- C2.1, in C2. Information structures not written yet
- C1.2.6, in C1. Basic concepts not written yet
Contents
Lists with access at the ends
Overview
Section 2.2.1 of TAOCP lists nine operations that a program may do on a linear list , such as to reach the th node, to insert or delete a node at place , to join two lists, to split a list, to copy a list and to count its nodes. No one representation makes all nine fast. So the book looks at lists where the work happens at the ends only, and it gives them names: stack, queue and deque. It also gives the notation and . The rest of the section is a set of 14 exercises on one question: if the items enter a list in this order, which orders can leave it? This chapter shows the answer with proofs and with tables. The sections that follow (2.2.2 to 2.2.6) show how to store these lists in memory, and Chapter 8 of the book uses the stack for recursion.
The ideas
Three lists, three rules. Think of a row of items with a left end and a right end.
| Kind | Where items go in | Where items go out | Name of the order |
|---|---|---|---|
| stack | one end, the top | the same end | last in, first out |
| queue | one end, the rear | the other end, the front | first in, first out |
| deque | either end | either end | none |
An input-restricted deque lets items in at one end only and out at both ends. An output-restricted deque lets items out at one end only and in at both ends. A stack and a queue are both special cases of a deque. A stack is an input-restricted deque that always takes its items out at the end where they went in. A queue is an input-restricted deque that always takes its items out at the other end.
A stack as a railway yard. Cars come on the input track in the order . A car can go into the stack, a short dead end, and a car can leave the stack to the output track. Only the car at the end of the dead end can leave. Write S for "a car goes from the input into the stack" and X for "a car goes from the stack to the output". The word of S and X that a switchman does is the code of the run. For example, with three cars: car 1 goes in, car 2 goes in, car 2 goes out, car 3 goes in, car 3 goes out, car 1 goes out. The output order is .
Three questions follow. Which words are meaningful (the stack is never empty when X is done)? Do two different meaningful words give two different output orders? Which output orders are possible? The sections below answer all three, first for the stack and then for the other lists.
Definitions, results and proofs
Definition C2.2.2.1.1 (the three kinds of list, TAOCP Section 2.2.1). A stack is a linear list in which all insertions and deletions, and usually all accesses, are at one end. A queue is a linear list in which all insertions are at one end and all deletions, and usually all accesses, are at the other end. A deque is a linear list in which all insertions and deletions, and usually all accesses, are at the two ends. An input-restricted deque takes insertions at one end only. An output-restricted deque takes deletions at one end only.
Node: 2.2.1-def-stack · Lean: not yet stated
Explanation. The words say which operations the program may use, not how the list sits in memory. A stack stored in an array and a stack stored as a chain of nodes are the same stack, if the same operations give the same results. The word "usually all accesses" says that a program may look at the end item without removing it.
Example. A list holds in this order from the left. As a stack with its top at the left end, a deletion gives and leaves . As a queue with its front at the left end, a deletion also gives . If the rear is at the right end, an insertion of gives . As a stack with the top at the left, the insertion of gives . So the two lists differ in the place of an insertion, not in the place of a deletion.
Definition C2.2.2.1.2 (the words of position, TAOCP Section 2.2.1). In a stack the end where items enter and leave is the top, and the other end is the bottom. In a queue items enter at the rear and leave from the front. In a deque the two ends are the left end and the right end.
Node: 2.2.1-def-terms · Lean: not yet stated
Explanation. The words are only names. Nothing moves in memory when an item goes onto a stack: the item is added at the top, and the other items stay where they are. The words "push" and "pop" are common, but this chapter uses "insert" and "delete" to keep this in mind.
Example. Take the queue with the front on the left. Item is at the front and item is at the rear. After one deletion the front is . After the insertion of the rear is and the list is .
Definition C2.2.2.1.3 (insertion, TAOCP eq. 2.2.1(1)). When is a stack, the statement inserts the value on the top of . When is a queue, it inserts at the rear of .
Node: 2.2.1-(1) · Lean: not yet stated
Explanation. One symbol serves both lists, since the algorithm that uses it does not need to say where the item goes. The kind of list says where.
Example. Let be an empty stack. After and the list from the top is . If is an empty queue instead, the same two statements give the list from the front to the rear.
Definition C2.2.2.1.4 (deletion, TAOCP eq. 2.2.1(2)). The statement sets the variable to the item at the top of the stack , or at the front of the queue , and deletes that item from . It has no meaning when is empty.
Node: 2.2.1-(2) · Lean: not yet stated
Explanation. A deletion from an empty list is an error that the program must prevent. In a program the test for an empty list comes before the deletion. Section 2.2.2 calls the error underflow.
Example. Take the lists of the previous example. For the stack , the statement gives and leaves . For the queue , it gives and leaves . A second statement on the stack gives and leaves the empty stack. A third has no meaning.
Definition C2.2.2.1.5 (the top, TAOCP eq. 2.2.1(3)). For a nonempty stack , is the item at the top of . It does not change .
Node: 2.2.1-(3) · Lean: not yet stated
Explanation. The function is the access that the definition of a stack allows without a deletion. It is not defined for an empty stack.
Example. For the stack from the top, and the stack still has two items. After the value is .
Theorem C2.2.2.1.6 (the admissible words, TAOCP exercise 2.2.1-3). A word of S and X with letters S and letters X is the code of a complete run on a stack of cars if and only if each prefix of the word has at least as many S as X. Two different admissible words give two different output orders.
Node: 2.2.1-res-admissible · Lean: not yet stated
Explanation. A word with this prefix property is called admissible. The first half is the rule "never delete from an empty stack": the stack holds (the number of S) minus (the number of X) cars after a prefix. The second half says that the output order tells the word back. The rule shows how to check a word by one pass with a counter.
Example. For the word has the prefix counts equal to , never below , so it is admissible. The word has the counts and it is not admissible: the third letter deletes from an empty stack. The words and are two admissible words, and they give and .
Proof. After a prefix with letters S and letters X the stack holds cars. An X needs a car, so must hold after each letter. This is the prefix rule, and it is enough, since then each X finds a car. Now let two admissible words give the same output, and suppose they differ. Let be the first place where they differ. The first letters are the same, so both runs have the same stack and the same next input car at this point. One word has X at the place and the other has S. Say the first word has X. It outputs the car at the top of the stack, and this is its th output, for some . In the second word the car stays in the stack, and the letter S puts a car above it. The th output of the second word is made by the next X after the place , and no X lies between. At that X the top of the stack is a car that lies above , so it is not . So the two outputs differ at the position .
Theorem C2.2.2.1.7 (the number of orders of a stack, TAOCP exercise 2.2.1-4). The number of orders of that a stack can make is
Node: 2.2.1-res-catalan · Lean: Mathlib catalan
Explanation. By the previous theorem, is the number of admissible words, so the proof counts the words. The numbers for are the Catalan numbers. Mathlib defines them as catalan n. This chapter does not name a lemma that links the two forms.
Example. For the formula gives . The five admissible words are SSSXXX, SSXSXX, SSXXSX, SXSSXX and SXSXSX, and they give the orders , , , and . The order is the only order of that the stack cannot make. For the formula gives of the orders.
Proof. There are words with letters S and letters X. Count the words that are not admissible. Such a word has a first place where the counter is . Swap S and X in all letters up to and including that place. The prefix had one more X than S, so the new prefix has one more S than X, and the whole word gets letters S and letters X. Conversely, take a word with letters S and letters X. Its counter goes from to in steps of , so it has a first place where the counter is . Swap the letters up to that place, and the counter at that place becomes for the first time. The two maps undo each other. So the number of inadmissible words is , and
Theorem C2.2.2.1.8 (the forbidden pattern, TAOCP exercise 2.2.1-5). A stack can turn into if and only if there are no indices with .
Node: 2.2.1-res-pattern · Lean: not yet stated
Explanation. The three values form the pattern : a large value, then a small one, then a middle one. A stack can never output a large car, then a small car, then a middle car, since the small and the middle car are both under the large car or before it, and the stack returns them in the reverse order of their input. The theorem makes the test for a given order easy to think about, and the next algorithm makes it easy to run.
Example. The order has no triple of this kind. The order has the triple , and also . So the first order is possible and the second is not. For the ten orders with the pattern are , , , , , , , , and , and .
Proof. Suppose that a stack gives the order and that with exist. Cars enter in the order , so when the car leaves, the cars and , which are smaller, have entered already. Both are still in the stack, since they leave later. They entered in increasing order, so is above , and must leave before . This contradicts . For the other half, assume that the order has no such triple and run the test of Algorithm 2.2.1-T below. If it fails, it fails at an output when the car is in the stack and a car lies above it. The car is not yet output, so with . The car entered the stack because an earlier output with was larger than (the test enters cars only up to the wanted one). So with , which is the forbidden pattern.
Theorem C2.2.2.1.9 (the queue, TAOCP exercise 2.2.1-6). A queue can give only one order of , the order itself.
Node: 2.2.1-res-queue · Lean: not yet stated
Explanation. A queue keeps the order of its items. So it cannot permute. The exercise has rating 00 for this reason.
Example. Put into a queue with any mix of insertions and deletions that is legal. Item is inserted first, so it is at the front, and it is the first to leave. Then is the front, and so on. The output is for each mix.
Proof. Items enter in the order , and the front item is always the oldest item in the queue. So the item that leaves is the oldest item that has not left. By induction the th item to leave is .
Result (the deques, TAOCP exercises 2.2.1-7 to 2.2.1-9). Let be the number of orders of that an input-restricted deque can make, and the number for an output-restricted deque. Let be the number for a general deque. Then for all , and the values are in the table. For the order is possible with an input-restricted deque only, the order with an output-restricted deque only, and the order with neither of the two.
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
|---|---|---|---|---|---|---|---|
| stack | 1 | 2 | 5 | 14 | 42 | 132 | 429 |
| queue | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| input-restricted | 1 | 2 | 6 | 22 | 90 | 394 | 1806 |
| output-restricted | 1 | 2 | 6 | 22 | 90 | 394 | 1806 |
| deque | 1 | 2 | 6 | 24 | 116 | 634 | 3762 |
Node: 2.2.1-res-deques · Lean: not yet stated
Explanation. The values come from a search over all states of the run (the deque content, the next input car and the cars output so far), done by python for this chapter. The proof of is in the X1 solution of exercise 9: a run on one kind of deque, read backward in time and with the cars renamed, is a run on the other kind. The general deque makes all orders for , and it misses of the orders for . These are , , and . No simple closed form for is known, and the question is open (the exercise has rating 48).
Example. The order with an input-restricted deque that takes items in at the right end only: insert , , , to get . Delete from the right to output . Delete from the left to output . Delete from the right to output , and then . The output is . The order with an output-restricted deque that takes items out at the left end only: insert to get ; insert at the left to get ; insert at the right to get ; insert at the left to get . Delete four times at the left to output .
Algorithms and programs
Algorithm C2.2.2.1.10 (can a stack make this order, TAOCP Section 2.2.1, exercise 2.2.1-5). The input is an order of . The output is "yes" with the code word of S and X, or "no".
Node: 2.2.1-alg-test · Lean: not yet stated
The idea. Read the wanted outputs one at a time. For the wanted car , move input cars into the stack until is at the top. If is already in the stack but not at the top, the order is not possible. Else delete .
The steps.
StackTest(p[1..n]):
T1: S := empty stack; next := 1; word := ""
T2: for m := 1 to n:
v := p[m]
while (S is empty or top(S) != v) and next <= n and v >= next:
S <= next; next := next + 1; word := word + "S"
if S is empty or top(S) != v: return "no"
x <= S; word := word + "X"
T3: return "yes", word
Invariant. At the start of each pass of the loop on , the stack holds, from the bottom to the top, an increasing list of cars from that are not yet output, and it holds all of them. The cars are still on the input. The loop on next keeps the stack increasing, since each car pushed is larger than all cars in the stack.
A worked run, a possible order. The order is . Each row is the state after the pass for the wanted car.
| Moves | Stack, bottom to top | next | word | ||
|---|---|---|---|---|---|
| start | empty | 1 | |||
| 1 | 2 | insert 1, insert 2, delete 2 | 1 | 3 | SSX |
| 2 | 3 | insert 3, delete 3 | 1 | 4 | SSXSX |
| 3 | 1 | delete 1 | empty | 4 | SSXSXX |
| 4 | 5 | insert 4, insert 5, delete 5 | 4 | 6 | SSXSXXSSX |
| 5 | 4 | delete 4 | empty | 6 | SSXSXXSSXX |
The answer is "yes" with the word , which is admissible.
A worked run, an impossible order. The order is .
| Moves | Stack, bottom to top | next | Result | ||
|---|---|---|---|---|---|
| start | empty | 1 | |||
| 1 | 2 | insert 1, insert 2, delete 2 | 1 | 3 | |
| 2 | 5 | insert 3, 4, 5, delete 5 | 1, 3, 4 | 6 | |
| 3 | 4 | delete 4 | 1, 3 | 6 | |
| 4 | 1 | none | 1, 3 | 6 | top is 3, not 1: "no" |
The failure shows the pattern. The car is above in the stack, and is not yet output. The car entered because an earlier output ( or ) was larger than . So the triple is of the form of the theorem.
Correctness. The test makes the only moves that can lead to the wanted car. Cars enter in increasing order, so the car can leave only when it is at the top. If it is in the stack and not at the top, a car above it must leave first, which is not what the order asks. If it is not in the stack, it is on the input and the test moves cars in until it is on the top. The loop ends, since each pass of the inner loop moves one car and each outer pass deletes one car.
Cost. The test inserts each car at most once and deletes each car at most once, so it does at most stack operations and at most comparisons with the top, whatever the order. The two runs above use and operations.
Algorithm C2.2.2.1.11 (a queue from two stacks, TAOCP exercise 2.2.1-14). The input is a series of insertions and deletions . The output is the same as for a queue. The program has two stacks, IN and OUT, and both are empty at the start.
Node: 2.2.1-alg-twostacks · Lean: not yet stated
The idea. New items go on IN. Items leave from OUT. When OUT is empty and a deletion comes, move all items from IN to OUT one by one. This reverses their order, so the oldest item is then on the top of OUT.
The steps.
Insert(x): IN <= x
Delete():
D1: if OUT is empty:
while IN is not empty: y <= IN; OUT <= y
D2: if OUT is empty: error (the queue is empty)
D3: x <= OUT; return x
Invariant. The queue, from the front to the rear, is the list OUT read from the top to the bottom, followed by the list IN read from the bottom to the top. Insert changes the end of that list, and a move from IN to OUT does not change the list.
A worked run. The operations are: insert , insert , delete, insert , delete, delete, insert , delete. Each row is the state after the operation. IN and OUT are shown from the bottom to the top.
| Operation | Result | IN | OUT | Items moved |
|---|---|---|---|---|
| start | empty | empty | ||
| insert | empty | 0 | ||
| insert | empty | 0 | ||
| delete | empty | 2 | ||
| insert | 0 | |||
| delete | empty | 0 | ||
| delete | empty | empty | 1 | |
| insert | empty | 0 | ||
| delete | empty | empty | 1 |
The outputs are , the order of the insertions, as for a queue.
Correctness. The invariant holds at the start, with both stacks empty. A move of one item from IN to OUT takes the top of IN, which is the newest item of IN, and puts it on the top of OUT. When all items have moved, OUT holds them with the oldest on the top, and then the list in the invariant is the same as before. The deletion takes the top of OUT, which is the front of the queue.
Cost. An item is inserted on IN once, moved at most once and deleted from OUT once, so it takes part in at most four stack operations (insert on IN, delete from IN, insert on OUT, delete from OUT). So queue operations with insertions cost at most stack operations in all, though one deletion alone can cost (the size of IN) stack operations. The run above has items and moves.
The exercises
The table has the 14 exercises of Section 2.2.1. The Markers column has the symbols of the book (M for mathematics, HM for higher mathematics).
| Exercise | Rating | Markers | Kind | Lean | Solution |
|---|---|---|---|---|---|
| 2.2.1-1 | 06 | K2 | not yet stated | X1, Exercise 2.2.1-1 | |
| 2.2.1-2 | 15 | K2 | not yet stated | X1, Exercise 2.2.1-2 | |
| 2.2.1-3 | 25 | K1 | not yet stated | X1, Exercise 2.2.1-3 | |
| 2.2.1-4 | 34 | M | K3 | Mathlib catalan |
X1, Exercise 2.2.1-4 |
| 2.2.1-5 | 28 | M | K1 | not yet stated | X1, Exercise 2.2.1-5 |
| 2.2.1-6 | 00 | K3 | not yet stated | X1, Exercise 2.2.1-6 | |
| 2.2.1-7 | 25 | K3 | not yet stated | X1, Exercise 2.2.1-7 | |
| 2.2.1-8 | 22 | K2 | not yet stated | X1, Exercise 2.2.1-8 | |
| 2.2.1-9 | 20 | M | K1 | not yet stated | X1, Exercise 2.2.1-9 |
| 2.2.1-10 | 25 | M | K1 | not yet stated | X1, Exercise 2.2.1-10 |
| 2.2.1-11 | 40 | M | K3 | not yet stated | X1, Exercise 2.2.1-11 |
| 2.2.1-12 | 34 | HM | K4 | not yet stated | X1, Exercise 2.2.1-12 |
| 2.2.1-13 | 48 | M | K9 | not yet stated | X1, Exercise 2.2.1-13 |
| 2.2.1-14 | 26 | K5 | not yet stated | X1, Exercise 2.2.1-14 |
Exercises 1 and 6 are quick checks of the definitions. Exercises 2 and 3 introduce the code of S and X, and this chapter proves the answer of exercise 3. Exercises 4 and 5 are the two theorems above. Exercises 7 to 9 compare the restricted deques, and the table above shows the counts. Exercise 8 asks if a general deque can make all orders. For it can, and for it misses the four orders listed. Exercises 10 and 11 count the orders of an output-restricted deque by a code of its own and by a generating function. Exercise 12 asks for the growth of and . Exercise 13 is open: the number of orders of a general deque has no known closed form, and the table above gives the first seven values. Exercise 14 is the queue from two stacks.
Lean
The repository tamnd/taocp-lean has no declaration for Chapter 2 yet, so nothing here is stated in Lean. Mathlib defines the Catalan numbers as catalan n, and the theorem above would say that the number of stack orders of cars equals catalan n. A formal model needs the three objects of the proofs: a word of S and X, the run of a stack on it, and the output order. Then "admissible" is a property of the word, and the theorems are statements about the map from admissible words to orders. The statements are not stated yet.
Notes and history
The railway picture of a stack is due to E. W. Dijkstra. Many names exist for the same lists. The stack is also the push-down list, the cellar and the LIFO list, and the queue is also the FIFO list. A deque is a "double ended queue", and it is pronounced like "deck". The count is the Catalan number named for Eugene Catalan. L. Euler found them for the problem of the cuts of a polygon into triangles, and Section 2.3.4.4 of the book meets the same numbers for binary trees. The forbidden pattern is an early example of a "pattern avoiding" class of orders, a topic that has its own literature today. The algorithm of Rosenstiehl and Tarjan, which the book quotes in exercise 13, decides in linear time if a given order is possible for a general deque.
Section 2.2.1 of TAOCP names three kinds of linear list: the stack, the queue and the deque. In each of them, insertions and deletions happen at the ends of the list only. The section gives the words and the notation that all later sections use, and it uses a railway switching yard to ask a question: which orders of can come out of such a list when the items go in in the order ? This chapter of C2 states the answer for the stack (the Catalan numbers and a forbidden pattern), for the queue (one order), and for the two restricted deques and the deque (counts found by exhaustive search). It adds two small algorithms that the book leaves to its exercises: a test that says if a given order can come out of a stack, and a queue built from two stacks. Both are run by hand and costed.
The source of this page. Something is wrong? Report it.