next up previous
Next: Deleting all occurrences of Up: Unit 12 Previous: Creation of a list

Deleting the first occurrence of an element from a list

To delete the first occurrence of an element elem from a list through iteration:

Observations:

Iterative implementation:

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

  boolean found = false;
  while ((p.next != null) && !found) {
    if (p.next.info.equals(s)) {
      p.next = p.next.next;       // delete the element
      found = true;               // forces exit of the loop
    } else
      p = p.next;
  }

  return lis.next;                // delete generator node
}

The recursive characterization and implementation are left as an exercise.


next up previous
Next: Deleting all occurrences of Up: Unit 12 Previous: Creation of a list