'Can't two different nodes point to the same node in a singly linked list?

I'm learning circular singly linked list and trying to learn how to delete the last node.

The instructor says, once you link the second last node to the first one, the link between the last node and the first node is automatically deleted. But can't two pointers point to a same object?



Solution 1:[1]

It is possible technically to have two pointers pointing to the same node. However, in the context of a singly linked list you can exclude that possibility, because the singly linked list is defined by a data and a next. We know that each node is linked to by exactly one other node, the previous one. The first node is linked to by the last node.

So, when you remove the last node of such a list, you have three main cases:

1. The list is empty

In this scenario your first element does not exist, so you do not need to remove anything.

2. The list has a single element

In this case, your list contains a single element, whose next points to itself. In this case, you will need to get rid of it.

3. The list has multiple elements

In this case you will need to:

  • find the penultimate node
  • set its next to point to the first node
  • get rid of the last node

Edge case

The data of the node may be some composite type and may contain pointers. If this fits your scenario, then you will need to make sure that you get rid of any references to the node you are to get rid of.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lajos Arpad