To delete the first occurrence of an element elem from a list through iteration:
Observations:
Example: Suppose we have to delete the element "B" from the list shown in the figure:
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.