Skip to content
Advertisement

Deleting the rear element of a circular linked list

I am trying various methods in a circular linked list in java and one of them is to delete the rear element. I’m pretty sure that my logic is correct but I think there is something wrong in my code.

The logic is to browse the list until cur.next is before the rear element and then delete it. Then I should link the new rear element to the head and initialize the new rear.

I am not getting error, it’s just that the wrong element is being deleted.
This is what I’m getting:
input: 8 | 4 | -8 | 5 | 10 | 3 | 4 | 8 |
output: 8 | 4 | 5 | 10 | 3 | 4 | 8 |

This is the method:

JavaScript

And this is the whole class:

JavaScript

Advertisement

Answer

The problem is in the insert method where you don’t assign the references properly in the general case (assuming insertion of tmp at the end of the list):

  • tmp.next should point to the first element (this.head) to have proper circularity [A]
  • this.rear.next (not this.head.next) should point to the new element [B]
  • this.rear should point to the element being inserted as it is now the new last element of the list [C]

Additionally, you are not assigning a self-reference to the single element of the list when inserting into an empty list in the special case [D].

Here is a working example of the insert method:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement