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:
public static IntList reverse (IntList list)
reverseTail
public static IntList reverseWhile (IntList list)
public static IntList reverseFor (IntList list)