Volume C2 · Information structures · TAOCP Section 2.2.5
Doubly linked lists
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.5 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.2.4, in C2. Information structures not written yet
- C1.3.1, in C1. Basic concepts not written yet
Two-way links and a discrete simulation
Overview
A doubly linked list has two links in each node, LLINK to the node on the left and RLINK to the node on the right. The extra link costs space and a few more assignments in each insertion. In exchange, a program that holds only the address of a node can delete it, and can insert a new node on either side of it, with no search. Section 2.2.5 of TAOCP shows why this matters on a large example: a discrete simulation, where many activities wait in one list sorted by time, and where an activity can be removed from the list before its time comes. This chapter explains the lists and their invariant, then the structure of the simulation and the rules of the elevator example, and it follows one user through a complete history.
The ideas
Two links make the neighbours of a node known. From a node , the node on the right is and the node on the left is . Going right and then left, or left and then right, comes back to . This is the two-way condition, and every operation must keep it.
A list head removes the special cases. The list head is a node that belongs to the list and holds no item. Its RLINK is the first item and its LLINK is the last item. The empty list has both links of the head pointing to the head. With a head, no node has a missing neighbour, so the delete and the insert have no cases for the ends.
Deletion needs only the address. To delete , link its two neighbours to each other. Both neighbours are known from . In a singly linked list the left neighbour is not known, and the program must have a second pointer that trails the first, as in Algorithm 2.2.4A.
Insertion changes four link fields. To insert a node to the right of , the program sets two links of and one link in each of the two old neighbours. A singly linked insertion sets two links.
A simulation keeps its future in a sorted list. A discrete simulation changes its state only at chosen instants. The program keeps a list of activities, each with the time of its next action, sorted by time. The clock jumps to the time of the first activity, and the program runs that activity. An activity that waits for time to pass is put back into the list at its new time.
Cancelling an activity needs a doubly linked list. An activity can be removed before its time, for example when a user gives up, or when an elevator door that was closing opens again. The program then holds the activity and must delete it from the agenda at once. This is the main reason for the doubly linked agenda.
Definitions, results and proofs
Definition C2.2.2.5.1 (a doubly linked list, TAOCP eqs. 2.2.5(1) and (2)). A node has the link fields LLINK and RLINK. A doubly linked list with a head and items has the nodes with , , , , and . The empty list has .
Node: 2.2.5-(1) · Lean: not yet stated
Explanation. The list is a circle with two directions. The head takes the place of the pointers LEFT and RIGHT of a list without a head, and the left and the right are exchangeable. For a list without a head, the book uses the two pointers LEFT and RIGHT for the ends, and a general deque on it is the subject of exercise 1.
Example. Let and the items be at . The links are given by the pairs (LLINK, RLINK): node has , node has , node has , node has . Reading to the right from the head gives . Reading to the left gives . The empty list is the one node with the pair .
Definition C2.2.2.5.2 (the two-way condition, TAOCP eq. 2.2.5(3)). The links of a list satisfy the two-way condition when and for every node of the list, the head included.
Node: 2.2.5-(3) · Lean: not yet stated
Explanation. The condition says that each right link is undone by the left link of its target, and the other way round. A list with a head, as defined above, satisfies it. The deletion and the insertion below keep it, and a program that breaks it in the middle of an operation must restore it before the next operation reads a link.
Example. In the list above take . Then and , and and . The same holds for the nodes , , .
Definition C2.2.2.5.3 (delete a node given its address, TAOCP eq. 2.2.5(4)). To delete the node from its list: , , and return to AVAIL.
Node: 2.2.5-(4) · Lean: not yet stated
Explanation. The two assignments make the left neighbour and the right neighbour of point at each other. For a list with a head, must not be the head, since the head is not an item. If is the only item, both neighbours are the head, and the result is the empty list. The two-way condition holds for all nodes that remain, which the next theorem shows.
Example. Delete the node from the list above. The left neighbour is and the right neighbour is . Set and . The pairs are now: node has , node has , node has . The list is and the node is free.
Definition C2.2.2.5.4 (insert a node to the right of a node, TAOCP eq. 2.2.5(5)). To insert a new item to the right of the node : take a node from AVAIL, , , , . The insertion to the left of is the same with left and right exchanged.
Node: 2.2.5-(5) · Lean: not yet stated
Explanation. The order of the four assignments matters. The third one reads , so it comes before the fourth, which changes . The insertion works for , which gives an insertion at the left end of the list, and for the last item, which gives an insertion at the right end.
Example. Insert to the right of the node , in the list with the node from AVAIL. Set , , , . The list is . Then insert to the left of the node , with the node : , , , . The list is .
Theorem C2.2.2.5.5 (the operations keep the two-way condition). If a list with a head satisfies the two-way condition, then the deletion of an item and the insertion of a new node next to a node of the list give a list that satisfies the two-way condition.
Proof. Let and before the deletion. By the condition, and . The deletion sets and . Now and , so the condition holds for and for . If , as in a list with one item, both assignments act on the head and the head is . No other node has a link that changed, and no remaining node has a link to , because the only links to were and .
For the insertion to the right of , let before the insertion. The new node has and . After the last two assignments, and . So and . For and the condition holds with between them, and no other link changed. The case , the head of an empty list, works the same way. The insertion to the left is the mirror image.
Explanation. The proof shows which links each operation touches, and the count is the cost. The deletion changes two link fields and the insertion changes four. The singly linked insertion of Section 2.2.3 changes two. The extra links are the price of the two-way access.
Example. A program checked the two-way condition on all nodes after each step of the examples above, that is, after the deletion of , the insertion of , the insertion of , and the deletion of all four items. The condition held every time, and the last list was the head with the pair .
Definition C2.2.2.5.6 (the node of an activity, TAOCP eq. 2.2.5(6)). An activity of the simulation is a node with the fields NEXTTIME, the time of its next action, and NEXTINST, the place where the action starts. It has two pairs of links: LLINK1 and RLINK1 put it in the agenda WAIT, and LLINK2 and RLINK2 put it in a list QUEUE or ELEVATOR. A user also has the fields IN and OUT, the floors of the start and of the destination.
Node: 2.2.5-(6) · Lean: not yet stated
Explanation. A user can be in the agenda, waiting for his patience to run out, and in a queue on a floor, at the same time. So a node of a user needs both pairs of links. The nodes for the actions of the elevator are only in the agenda, and need only the first pair.
Example. A user who waits at floor has a node with , , U4 and if the user gives up at time . The node is in WAIT by LLINK1 and RLINK1, and in QUEUE[0] by LLINK2 and RLINK2.
Algorithms and programs
Program C2.2.2.5.7 (the agenda of the simulation, TAOCP Program 2.2.5, the list routines). The agenda WAIT is a doubly linked list with a head whose NEXTTIME is smaller than any time. The nodes are sorted by NEXTTIME from left to right, and a node that is inserted goes after all nodes with the same time. The routines act on the current node .
Node: 2.2.5-prog-agenda · Lean: not yet stated
The routines. The first four put into the agenda, and the last two take the next action.
SORTIN(t): NEXTTIME(C) := t
P := LLINK1(WAIT) start at the right end
while t < NEXTTIME(P): P := LLINK1(P)
insert C to the right of P by the rule (5)
IMMED: NEXTTIME(C) := TIME; insert C to the right of the head WAIT
HOLD(d): SORTIN(TIME + d)
DELETEW: delete C from WAIT by the rule (4)
CYCLE: C := RLINK1(WAIT); TIME := NEXTTIME(C)
DELETEW; continue at NEXTINST(C)
Invariant. At each moment the agenda satisfies the two-way condition, and the times along the links from the head are nondecreasing. Among nodes of equal time, the one inserted first is nearer to the head. The head has the time , which stops the scan of SORTIN at the head.
Why it holds. SORTIN stops at the first node from the right with . All nodes to the right of have times larger than . After the insertion, is between and its old right neighbour, so the order is kept, and a node of equal time stays on the left of . The head has a time smaller than every NEXTTIME, so the scan ends. CYCLE takes the first node, which has the smallest time, so the clock never goes back.
Cost. SORTIN compares with once for each node from the right end to the place of , and once more at the stopping node. If nodes of the agenda have a time larger than , SORTIN makes comparisons. The scan from the right is a good choice when a new activity is likely to be late, as for a user who waits for a long time. IMMED and DELETEW take a fixed number of steps. DELETEW works for a node at any place, which is the reason for the double links.
Run. The program that made the history below counted insertions into the agenda, with comparisons in total, about per insertion. The agenda never had more than nodes. The book gives the profile of a longer run of its own program, in which the loop of the scan was the most frequent part, and the same loop would be the first one to improve.
Coroutine 2.2.5U (the users, TAOCP Coroutine 2.2.5U). A user enters, calls the elevator, waits in the queue of the floor, gets in, rides, and leaves. A user can give up while waiting.
Node: 2.2.5-alg-U · Lean: not yet stated
The steps.
U1: choose IN, OUT, GIVEUP (time of patience), INTER (time to the next user)
schedule the next user at TIME + INTER
U2: if FLOOR = IN and the elevator is about to close its doors (at E6):
send the elevator to E3, so that the doors open again; go to U3
if FLOOR = IN and the doors are open and nobody moves (D3 != 0):
D3 := 0; D1 := nonzero; restart E4; go to U3
otherwise: press UP or DOWN on floor IN, by the sign of OUT - IN
if D2 = 0 or the elevator is at E1: run subroutine D
U3: put the user at the rear of QUEUE[IN]; wait GIVEUP time units
U4: if FLOOR != IN or D1 = 0: the user leaves the queue and the system
else the user stays and waits for E4
U5: (sent by E4) the user leaves QUEUE[IN] and enters ELEVATOR
CALLCAR[OUT] := 1
if STATE = NEUTRAL: STATE := GOINGUP or GOINGDOWN by the sign of OUT - FLOOR
and E5 is set to run after 25 time units
U6: (sent by E4 at the destination) the user leaves ELEVATOR and the system
Invariant. A user is in exactly one of these places: waiting in a queue (with a pending U4 in the agenda), riding in ELEVATOR, or gone. A user in a queue is also a node of the agenda, until E4 sends the user to U5. Then the node is deleted from the agenda at once, and this is the cancelling of U4.
Cost. A user does constant work for each step. The user nodes are taken from AVAIL and returned to it, and the number of nodes in use is the number of users in the system.
Coroutine 2.2.5E (the elevator, TAOCP Coroutine 2.2.5E). The elevator has a floor FLOOR, a state STATE with the values GOINGUP, GOINGDOWN and NEUTRAL, and the flags D1 (people move), D2 (zero when the elevator has been still for 30 seconds or more) and D3 (the doors are open and nobody moves). The call tables are CALLUP, CALLCAR and CALLDOWN, one value for each floor. Times are in tenths of a second.
Node: 2.2.5-alg-E · Lean: not yet stated
The steps.
E1: wait at floor 2 with the doors closed (the home floor)
E2: if STATE = GOINGUP and no call exists above FLOOR:
STATE := NEUTRAL if no CALLCAR below FLOOR, else GOINGDOWN
clear the three calls of FLOOR
(the same with up and down exchanged for GOINGDOWN)
E3: D1 := D2 := nonzero
schedule E9 after 300, E5 after 76 (cancel and reset if already scheduled)
wait 20 (the doors open); go to E4
E4: if a user in ELEVATOR has OUT = FLOOR: send the latest such user to U6
else if QUEUE[FLOOR] is not empty: send its front user to U5
in both cases wait 25 and repeat E4
else D1 := 0; D3 := nonzero; wait for E5 or U2
E5: if D1 != 0: wait 40 and repeat E5
else D3 := 0; schedule E6 after 20
E6: clear CALLCAR[FLOOR]; clear CALLUP[FLOOR] if STATE != GOINGDOWN
clear CALLDOWN[FLOOR] if STATE != GOINGUP; run subroutine D
if STATE = NEUTRAL go to E1
if D2 != 0 cancel E9
wait 15, then go to E7 if GOINGUP, to E8 if GOINGDOWN
E7: FLOOR := FLOOR + 1; wait 51
if CALLCAR[FLOOR] or CALLUP[FLOOR], or
((FLOOR = 2 or CALLDOWN[FLOOR]) and no call above FLOOR):
wait 14; go to E2
else repeat E7
E8: the same downward, with the waits 61 and 23
E9: D2 := 0; run subroutine D
Invariant. The elevator is in one of the states of the diagram above, and the flags show which one: D1 while people get in or out, D3 with open doors and no motion. The activities E5 and E9 are independent of the main action of the elevator, so the elevator has three nodes in the agenda at most: the node of E1 to E4 and E6 to E8, the node of E5 and the node of E9.
Cost. An activity E7 or E8 runs once for each floor passed. The steps E4 repeat once for each person who gets in or out. The rest is constant for each stop.
Subroutine 2.2.5D (the decision, TAOCP Subroutine 2.2.5D). Subroutine D picks a direction when the elevator is NEUTRAL. It is run by U2, E6 and E9.
Node: 2.2.5-alg-D · Lean: not yet stated
The steps.
D1: if STATE != NEUTRAL: return
D2: if the elevator is at E1 and a call exists on floor 2:
schedule E3 after 20; return
D3: j := the smallest floor != FLOOR with a call
if no such j: if the caller is E6 then j := 2 else return
D4: if FLOOR > j: STATE := GOINGDOWN; if FLOOR < j: STATE := GOINGUP
D5: if the elevator is at E1 and j != 2: schedule E6 after 20
return
Invariant. After D returns, the state is NEUTRAL only if no floor other than FLOOR has a call, or if FLOOR is the destination j. In the second case the elevator stays, or the E6 of the caller sends it to E1.
Cost. A fixed number of steps, with one scan of the five floors in D3.
Run. The elevator is at floor in the state NEUTRAL with the doors closed, at E1, with no call. One user enters at time on floor and wants floor , with time units of patience. The program of the coroutines was run on a model that keeps WAIT as a real doubly linked list and checks the two-way condition after each change. Each row shows the activity run, its effect, and the agenda after it. The agenda always holds a far node USER1 at time for the next user, which is not shown. The activity names carry the time: E8@96 means that the elevator continues at E8 at time .
| Time | Step | Effect | FLOOR, STATE | Agenda after the step |
|---|---|---|---|---|
| 0 | U1, U2, U3 | the user enters at floor 0, presses UP, subroutine D sets GOINGDOWN and schedules E6, the user joins QUEUE[0] | 2, GOINGDOWN | E6@20, U4@400 |
| 20 | E6 | CALLDOWN[2] cleared, the elevator starts down | 2, GOINGDOWN | E8@35, U4@400 |
| 35 | E8 | the car leaves floor 2 and is on floor 1 | 1, GOINGDOWN | E8@96, U4@400 |
| 96 | E8 | no call at floor 1, the car goes on to floor 0 | 0, GOINGDOWN | E8@157, U4@400 |
| 157 | E8 | CALLUP[0] is set and no call is below, so the car stops | 0, GOINGDOWN | E2@180, U4@400 |
| 180 | E2, E3 | STATE becomes NEUTRAL, the calls of floor 0 are cleared, the doors open, E9 is set to 480 and E5 to 256 | 0, NEUTRAL | E4@200, E5@256, U4@400, E9@480 |
| 200 | E4 | the user gets in (U5): CALLCAR[2] is set, STATE becomes GOINGUP, E5 moves to 225, U4 is cancelled | 0, GOINGUP | E5@225, E4@225, E9@480 |
| 225 | E5 | D1 is not zero, the doors flutter, E5 repeats at 265 | 0, GOINGUP | E4@225, E5@265, E9@480 |
| 225 | E4 | QUEUE[0] is empty, D1 becomes 0 and D3 nonzero | 0, GOINGUP | E5@265, E9@480 |
| 265 | E5 | D1 is zero, the doors close, E6 is set to 285 | 0, GOINGUP | E6@285, E9@480 |
| 285 | E6 | CALLUP[0] cleared, D2 is nonzero, so E9 is cancelled | 0, GOINGUP | E7@300 |
| 300 | E7 | the car leaves floor 0 and is on floor 1 | 1, GOINGUP | E7@351 |
| 351 | E7 | no call at floor 1, the car goes on to floor 2 | 2, GOINGUP | E7@402 |
| 402 | E7 | CALLCAR[2] is set, so the car stops | 2, GOINGUP | E2@416 |
| 416 | E2, E3 | STATE becomes NEUTRAL, the calls of floor 2 are cleared, the doors open, E9 is set to 716 and E5 to 492 | 2, NEUTRAL | E4@436, E5@492, E9@716 |
| 436 | E4 | the user leaves (U6) | 2, NEUTRAL | E4@461, E5@492, E9@716 |
| 461 | E4 | nobody else, D1 becomes 0 and D3 nonzero | 2, NEUTRAL | E5@492, E9@716 |
| 492 | E5 | D1 is zero, the doors close, E6 is set to 512 | 2, NEUTRAL | E6@512, E9@716 |
| 512 | E6 | subroutine D finds no call, the state stays NEUTRAL, the elevator waits at E1 | 2, NEUTRAL | E9@716 |
| 716 | E9 | D2 becomes 0, subroutine D finds no call and does nothing | 2, NEUTRAL | empty |
The user waits time units for the doors to open on floor (20 seconds), gets in, and leaves the car at time . The cancellation of U4 at time is the case where the doubly linked agenda is needed: the node of the user is somewhere in the middle of the agenda, at the time , and it is deleted by its address. The cancellation of E9 at time is the same operation.
Analysis C2.2.2.5.8 (the counts of a profile, TAOCP Section 2.2.5). A profile of a run counts how many times each instruction runs, and shows which part of the program needs work. For the simulation, the quantities of interest are the number of calls of SORTIN, the number of comparisons in its loop, and the number of runs of CYCLE.
Node: 2.2.5-anal-profile · Lean: not yet stated
Explanation. In the history above, SORTIN ran times and made comparisons. Each activity that waits for time to pass costs one SORTIN, and each stop of the elevator costs a few. The loop of the scan is the part that grows with the number of nodes in the agenda, since each comparison passes one node. In a run with many users the loop dominates. The book reports this for a run of time units with users, and observes that the loop of SORTIN runs more often than any other. A cheap gain is to write the body of DELETEW in the place of its call in CYCLE.
Example. If the agenda holds nodes and a new node is later than of them, the scan from the right makes comparisons, and a scan from the left would make . In the history, the node USER1 at time is at the right end, so each scan from the right passes it, and a scan from the left would stop before it.
The exercises
The table has the 12 exercises of Section 2.2.5. The Kind column is the kind that X1 gives to its solution.
| Exercise | Rating | Markers | Kind | Lean | Solution |
|---|---|---|---|---|---|
| 2.2.5-1 | 21 | K5 | not yet stated | X1, Exercise 2.2.5-1 | |
| 2.2.5-2 | 22 | informal | not yet stated | X1, Exercise 2.2.5-2 | |
| 2.2.5-3 | 22 | informal | not yet stated | X1, Exercise 2.2.5-3 | |
| 2.2.5-4 | 24 | informal | not yet stated | X1, Exercise 2.2.5-4 | |
| 2.2.5-5 | 20 | K1 | not yet stated | X1, Exercise 2.2.5-5 | |
| 2.2.5-6 | 23 | K5 | not yet stated | X1, Exercise 2.2.5-6 | |
| 2.2.5-7 | 25 | informal | not yet stated | X1, Exercise 2.2.5-7 | |
| 2.2.5-8 | 21 | K6 | not yet stated | X1, Exercise 2.2.5-8 | |
| 2.2.5-9 | 23 | K6 | not yet stated | X1, Exercise 2.2.5-9 | |
| 2.2.5-10 | 40 | informal | not yet stated | X1, Exercise 2.2.5-10 | |
| 2.2.5-11 | 21 | K5 | not yet stated | X1, Exercise 2.2.5-11 | |
| 2.2.5-12 | 22 | informal | not yet stated | X1, Exercise 2.2.5-12 |
Exercises 1 and 2 are on the doubly linked list as a deque: the operations at the left end, and the reason why a singly linked list cannot do the same. Do them first, with the definitions above. Exercises 3 to 7 ask about the rules of the elevator and one bug. Exercise 4 is on the activity E9, which the history above sets at times and , and cancels in the first case only. Exercises 8 and 9 ask for the code of E8 and of subroutine D, and the pseudocode of this chapter gives their logic. Exercise 10 is an open project. Exercise 11 is on synchronous simulation. Exercise 12 asks why the lists of the simulation are doubly linked, and the cancellations in the run above are the answer in short form.
Lean
The repository tamnd/taocp-lean has no declaration for Chapter 2, so nothing here is stated in Lean. A model of the doubly linked list needs two partial maps from addresses to addresses, LLINK and RLINK, with the two-way condition as a statement that they are inverse of each other on the nodes of the list. The theorem on the deletion and the insertion is then a statement about the update of two maps. No Mathlib name is claimed here.
Notes and history
The book builds the simulation on the elevator of the mathematics building of a university, and it gives a table of one history of the system and the full program in MIX. This chapter uses a different, short history, made with a model of the rules, and it does not give the program. The agenda holds, for each activity, the time and the place where it continues. The text of the section marks the double links as the reason to choose them for the lists of the simulation, and exercise 12 asks the reader to say why.
Section 2.2.5 of TAOCP gives each node two links, one to each neighbour. A node can then be deleted when only its address is known, and a node can be inserted on either side of a known node. The section uses these two abilities in a discrete simulation of an elevator, where activities wait in a list sorted by time and some of them are cancelled before they run.
The chapter has one file. It defines the doubly linked list with a list head and shows that deletion and insertion keep the two-way invariant. It then explains the agenda of a simulation as a sorted doubly linked list, the routines on it, the rules of the users, the elevator, and the decision subroutine, and a complete history of one user, computed by a program that keeps the agenda as a real doubly linked list and checks the invariant after each change.
Read Sections 2.2.3 and 2.2.4 first. The exercises of this section have files in X1, and the exercise table links to them.
The source of this page. Something is wrong? Report it.