next up previous
Next: Deleting the first occurrence Up: Unit 12 Previous: Inserting a new element

Creation of a list whose elements are read from a file

We want to create a list by reading its elements from a file, and we want the order of the elements to be as in the file. This means that each newly read element must be inserted at the end of the list.

To avoid that for each new element read from the file we have to scan the entire list already constructed, we maintain a reference to the last element read.

Example: If the first three lines of the file contain the strings "A", "B", and "C" in that order, the third element of the list is concatenated to the preceding ones as shown here:

For the iterative implementation, to avoid having to deal separately with the first element of the list, we use the generator node technique:

Iterative implementation:

public static ListNode read(BufferedReader br) throws IOException {
  // note: the value EOF (^D) in input terminates the insertion
  ListNode lis = new ListNode();    // create generator node
  ListNode p = lis;

  String s = br.readLine();
  while (s != null) {
    p.next = new ListNode();        // note: p.next.next == null
    p = p.next;
    p.info = s;
    s = br.readLine();
  }

  lis = lis.next;                   // delete generator node
  return lis;
}

The recursive characterization and implementation are left as an exercise.


next up previous
Next: Deleting the first occurrence Up: Unit 12 Previous: Inserting a new element