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:

• we scan the list searching for elem;
• if elem does not appear in the list, then we do nothing;
• otherwise, depending on where elem appears in the list, we distinguish three cases:
1. elem is the first element of the list: we return the reference to the second element of the list;
2. elem is neither the first element nor the last element of the list: we update the next field of the element preceding elem in such a way that it points to the element following elem;
3. elem is the last element of the list: as case 2, with the only difference that the next field of the preceding element is set to null.

Observations:

• To be able to update the next field of the element preceding elem, we have to stop scanning the list when we have a reference to the element preceding elem (and not when we have reached elem itself).

Example: Suppose we have to delete the element "B" from the list shown in the figure:

• To stop scanning the list after we have found and deleted the element, we use a boolean sentinel.
• To avoid having to deal separately with the first element, we can again use the generator node technique.

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: Deleting all occurrences of Up: Unit 12 Previous: Creation of a list