next up previous
Next: Example: palindrome string Up: Unit 11 Previous: Evolution of the stack

Example: the last ones will be the first ones (cont'd)

Let us consider again the example in which we read the lines of a file (which we access through a BufferedReader) and copy them to an output stream, inverting the order of the lines in the file.

For simplicity, we repeat here the recursive implementation we have seen before:

public static void copyInverse(BufferedReader br, PrintStream p) throws IOException {
  String s = br.readLine();
  if (s != null) {
    copyInverse(br, p);
    p.println(s);
  }
}

At this point it is clear that the successive lines of the file are stored in the strings that we can access through successive occurrences of the variable s in the ARs of the successive recursive calls of copyInverse(). Hence, the stack of ARs is used as a temporary ``data structure'' in which to store the lines of the file before printing them.

To implement this method in an iterative way, we would have to read all lines of the file and store them, before we could start printing. Since we could not use the stack of ARs, we would need an additional data structure, e.g., an array of strings.


next up previous
Next: Example: palindrome string Up: Unit 11 Previous: Evolution of the stack