next up previous
Next: Deleting all occurrences of Up: Unit 12 Previous: Deleting the first occurrence

Deleting all occurrences of an element from a list

To delete all occurrences of an elements from a list, we can proceed as for the deletion of the first occurrence. The differences are that:

Observations:

Iterative implementation:

public static ListNode deleteAll(ListNode lis, String s) {
  ListNode p = new ListNode();    // create the generator node
  p.next = lis;
  lis = p;

  while (p.next != null) {
    if (p.next.info.equals(s))
      p.next = p.next.next;       // delete the element
    else
      p = p.next;
  }

  return lis.next;                // delete generator node
}


next up previous
Next: Deleting all occurrences of Up: Unit 12 Previous: Deleting the first occurrence