Prelab 9

The problem below was covered in Thursday lecture. Please review your lecture notes and also read the additional notes on this example and iteration in general in preparation for lab.

Iterative List Reversal

In lab last week, we studied the following recursive method for reversing a list:
public static IntList reverse (IntList L) {
  if (isEmpty(L)) {
    return empty();
  } else {
    return postpend(reverse(tail(L)), head(L));
  }
}

public static IntList postpend (IntList L, int n) {
  if (isEmpty(L)) {
    return prepend(n, empty());
  } else {
    return prepend(head(L), postpend(tail(L), n));
  }
}

An alternative technique for reversing a list is to follow the strategy one would use in reversing a pile of cards: form a new pile by iteratively removing the top card of the original pile and putting it on the new pile. When there are no more cards in the original pile, the new pile contains the cards in reverse order from the original pile.

Based on this idea, here is a table corresponding to an iterative reversal of the list [1,2,3,4]:
list result
[1,2,3,4] []
[2,3,4] [1]
[3,4] [2,1]
[4] [3,2,1]
[] [4,3,2,1]

Implement this iterative list reversal strategy in a reverse() method in three ways:

  1. using tail recursion to implement the iteration
    public static IntList reverse (IntList list)
    Name the auxiliary method reverseTail

  2. using a while loop implement the iteration
    public static IntList reverseWhile (IntList list)

  3. use a for loop to implement the iteration
    public static IntList reverseFor (IntList list)