next up previous
Next: Summary of the graphical Up: Unit 12 Previous: Deleting all occurrences of

Deleting all occurrences of an element from a list - recursive version

We can characterize recursively the operation of deleting all occurrences of an element elem from a list lis as follows:

  1. if lis is the empty list, then return the empty list (base case);
  2. otherwise, if the first element of lis is equal to elem, then return the list obtained by deleting all occurrences of elem from the rest of lis (recursive case);
  3. otherwise, return the list whose first element coincides with the first element of lis, and whose rest is obtained by deleting all occurrences of elem from the rest of lis (recursive case).

Recursive implementation:

public static ListNode deleteAll(ListNode lis, String s) {
  if (lis == null)
    return null;
  else if (lis.info.equals(s))
    return deleteAll(lis.next, s);
  else {
    lis.next = deleteAll(lis.next, s);
    return lis;
  }
}

Note: It does not make sense to apply the generator node technique when we implement an operation on lists using recursion. Such a technique makes only sense for an iterative implementation, and typically only when the list is modified by the operation.


next up previous
Next: Summary of the graphical Up: Unit 12 Previous: Deleting all occurrences of