I tried to implement a circularly linked list and I had read that the complexity of removing the tail (which has a direct reference) is O(1). However I can't get rid of the tail reference without looping and resulting in a complexity of O(n) and so I was wondering if this is at all possible without looping?
remove = tail;
prev = temp = tail.getNext();
do
{
prev = temp;
temp = temp.getNext();
}
while(!temp.getNext().equals(tail.getNext()));
prev.setNext(temp.getNext());
size--;
return remove;
Note: prev, temp, removeare local and tail is the tail of the list and first instance of tail.getNext() is the head.
I had tried the below as well but it does not work as the node before tail still points to tail and the reference isn't removed. I know that I need make the tail's previous point to the head in order to remove the tail and the above code does this, but I'm just unsure how to do this and if it's possible without looping through the list..
remove = tail;
tail= lastNode.getNext();
size--;
return remove;