next up previous
Next: Creation of a list Up: Unit 12 Previous: Inserting a new element

Inserting a new element as the last one of a list - recursive version

Recursive characterization of the insertion of elem as the last element of lis:

  1. if lis is the empty list, then return the list constituted only by one node containing elem (base case);
  2. otherwise, return the list whose first element coincides with the one of lis, and whose rest is obtained by inserting elem in the rest of lis (recursive case).

Recursive implementation:

public static ListNode insertLast(ListNode lis, String s) {
  if (lis == null) {
    ListNode res = new ListNode();    // note: res.next == null
    res.info = s;
    return res;
  } else {
    lis.next = insertLast(lis.next, s);
    return lis;
  }
}


next up previous
Next: Creation of a list Up: Unit 12 Previous: Inserting a new element