Deleting a Node from the tail in a circular linked list in Java

68 Views Asked by At

The code that I'm trying to understand is below

public void deleteNodeFromTail() {
    System.out.println('\nDeleting Node ' + tail.element + ' from Tail');

    if(tail.next == tail) {
        tail = null;
    }

    Node newTail = tail;
  
    while(newTail.next != tail) {
        newTail = newTail.next;
    }

    newTail.next = tail.next;
    tail = newTail;
}

How exactly is this deleting a node from the tail in a circular linked list?

I have a linked list of [50, 75, 100, 25] and I walked through this step by step:

The first step says that if (tail.next) == tail, tail = null. In this case 50 isn't equal to 25, so that would be skipped.

Node newTail is declared and is assigned whatever the value of tail is, which is 25. The issue here is that I don't know what newTail is doing or how it's relating to the other nodes in the list. It looks to be a temp variable to hold a value, but I don't know the significance of why another node is being declared here.

Next, newTail is made equal to newTail.next as long as newTail.next isn't equal to tail. Again, I don't know whether newTail, should be considered part of the list, or the significance of newTail beyond being a temp variable to assign a value to another part of the list. I'm assuming that newTail is now part of the linked list, so we have [50, 75, 100, 25, 25]. This doesn't make sense.

From there I don't know what to do. The while loop seems like it would be an infinite loop. I'm also not seeing where the deletion itself happens, or how that's possible just by assigning values without actually decrementing the list.

1

There are 1 best solutions below

0
Mike Nakis On

I don't know "how exactly [this is] deleting a node from the tail", and I don't have any reason to believe that it does. You can post any nonsensical code and ask us to figure out why it does what you allege it does, but the first question is, does it actually do that?

The following lines:

    tail = null;
}
Node newTail = tail;
while(newTail.next

will, on occasion, cause a null pointer exception at newTail.next. So, this code is highly suspicious. So, unless you tell us where you found it, and why you believe it does what you allege it does, we have no reason to look at it any further.