32C. Example: Reversing a List

Let's define function reverse(L), which returns the reversal of list L. For example, reverse([2, 4, 6, 8]) = [8, 6, 4, 2]. Think of the list as a deck of cards. To reverse the deck, start with it in your hand. Remove a card from the top of the deck and place it in a stack of cards on a table. Keep doing that until there are no more cards in your hand. The deck on the table is the reversed deck. Showing the process just before moving each card gives the following plan.

 hand      table 
[2, 4, 6, 8]    [ ]
[4, 6, 8]    [2]
[6, 8]    [4, 2]
[8]    [6, 4, 2]
[ ]    [8, 6, 4, 2]

Now it is just a matter of expressing that in C++.

  List reverse(ConstList L)
  {
    ConstList hand  = L;
    List      table = emptyList;

    while(!isEmpty(hand))
    {
      table = cons(head(hand), table);
      hand  = tail(hand);
    }
    return table;
  }

A loop invariant for the loop in reverse is as follows, where we use x ++ y to indicate the concatenation of lists x and y.

(reverse-invariant)   reverse(hand) ++ table = reverse(L).

What does that tell you about the value of variable table when hand is [ ]?