Proofs: Linked list
These are the human proofs of Linked list, at full length.
The linked list operations keep the chain and return the right result full
This proof shows: correctness.
Setting. For a list , the chain of is the sequence of nodes , , up to the first NIL.
Invariant (I). The chain of has exactly nodes , they are distinct, and $v_{n-1}.next = $ NIL (or $L.head = $ NIL when ). The list held is .
We show that each operation, started in a state where (I) holds and its precondition holds, ends with (I) for the list that the list type asks for. Write for the old keys. A new node made in line L1 or L4 is not in the old chain, because it did not exist before.
PUSH-FRONT. Line L1 makes a new node with key . Line L2 sets (or NIL if ). Line L3 sets and the count to . The new chain is : these are distinct nodes, because is new and the old nodes are distinct, and the old fields did not change, so the chain still ends at NIL after . The list held is .
INSERT-AFTER, for some . Line L4 makes a new node . Line L5 sets to the old , which is , or NIL when . Line L6 then sets . Only the field of and of are written. So the new chain is , and it ends at NIL. These nodes are distinct, and the count is . The list held is . Line L5 reads before line L6 changes it; that order is what makes the old successor.
DELETE-FRONT, . Line L7 sets . Line L8 sets (or NIL if ) and the count to . No field changes, so the new chain is , with distinct nodes, ending at NIL. Line L9 returns , and the list held is .
DELETE-AFTER, with . The precondition NIL means . Line L10 sets . Line L11 sets , which is or NIL, and the count to . Only the field of changes. The new chain is : distinct nodes ending at NIL. Line L12 returns , and the list held is the old list without position .
SEARCH. Loop invariant: at the test of line S2, for some (with meaning NIL), and for every . It holds with after line S1. If the test passes, then NIL and , and line S3 moves to , so the invariant holds for . The value grows by 1 in each iteration and cannot pass , because at the test fails on $p = $ NIL; by (I) the chain has nodes and no cycle, so the loop ends after at most iterations. At exit, either $p = $ NIL and , so no key equals and NIL is right, or with and no earlier key equal to , so is the first node with key .
NODE-AT, . After line S5 , and each of the steps of line S6 moves from to for , so no step reads NIL. Line S7 returns .