next up previous
Next: Accessing successive nodes of Up: Unit 12 Previous: Inserting a new element

Deleting the first element of a list

In general, deleting an element of a list means to modify the list in such a way that the element is no longer connected to its predecessor and successor, while bridging the deleted element to maintain the connection of the other elements.

To delete the first element of a list we proceed as follows: -

Implementation:

public static ListNode deleteFirst(ListNode lis) {
  if (lis != null)
    lis = lis.next;
  return lis;
}

Note that the method works correctly also in the case where the element to delete is the only one of the list (i.e., when the value of lis.next is null). In this case, the method returns the empty list (i.e., null).

Note: The possibility of deleting a node by simply modifying the reference to it in such a way that this reference points to the following node, without needing to take care of releasing the occupied memory, is a peculiarity of Java (and in general, of those languages that make use of garbage collection for the dynamic management of objects). Indeed, the garbage collector will take care of checking whether the ``deleted'' node is not referenced anymore, and hence the memory occupied by it can be made available on the heap for other objects. Other programming languages, such as Pascal, C, or C++, require that the programmer explicitly frees the memory occupied by those objects that are not needed anymore.


next up previous
Next: Accessing successive nodes of Up: Unit 12 Previous: Inserting a new element