Proofs: In-place linked list reversal
These are the human proofs of In-place linked list reversal, at full length.
REVERSE returns the same nodes in reverse order full
This proof shows: correctness, termination.
Claim. Let be the first node of an acyclic singly linked list with nodes (), so that for and , and when . Then REVERSE stops after exactly iterations of the loop of line L3. It returns (nil when ), and after the call for and . No other field of any node changes, and no node is created.
Setup. Write and . Count the iterations of the loop with , so that at the first test of line L3. The invariant at the test of line L3 after iterations is:
(R) , , , for , and for .
The third part says that the list from is . The last part says that the list from is , with its old links.
Step 1 (initialization). Lines L1 and L2 set and (both nil when ). No link has changed, so for , and the condition for is empty. So (R) holds with .
Step 2 (maintenance). Assume (R) for some , and that the test of line L3 succeeds, so . Since and is nil only for , we have , and is the real node . By the last part of (R) with , line L4 sets . Line L5 sets . This is the only write to a node field in the iteration, so the links of every other node stay as (R) states. Lines L6 and L7 set and . Now holds for , and holds for . So (R) holds for , and .
Step 3 (termination). By (R), at each test of line L3, and each iteration increases by exactly 1. So the quantity is a non-negative integer that drops by exactly 1 in each iteration, and the loop runs at most times. The loop cannot stop while , because then is a node, not nil. So it stops exactly when , after iterations.
Step 4 (conclusion). At exit, (R) holds with : , and for , that is, for and . Line L8 returns . The only writes to node fields are the writes of line L5, one to the next field of each node, and the algorithm creates no node.