next up previous
Next: Searching an element in Up: Unit 12 Previous: Lists as inductive structures

Printing the elements of a list - recursive version

We can characterize recursively the operation of printing the elements of a list as follows:

  1. if the list is empty, don't do anything (base case);
  2. otherwise, print the first element, and then print recursively the rest of the list (recursive case).

Recursive implementation:

public static void print(ListNode lis, PrintStream ps) {
  if (lis == null)
    ps.println();                 // base case
  else {
    ps.print(lis.info + " ");     // process the first element
    print(lis.next, ps);          // recursive call
  }
}


next up previous
Next: Searching an element in Up: Unit 12 Previous: Lists as inductive structures