Search code examples
javadata-structureslinked-listsingly-linked-list

Delete Last node of Linked List in Java when the head is not given


I was solving the problem to delete the middle node of a LinkedList. Say given a linked list a->b->c->d->e you would want to delete b/c/d and the head of the LinkedList is not given.

    public boolean deletemiddle(LinkedListNode node) {
        if(node==null)
            return false;
        LinkedListNode n=node;
        node.data=n.next.data;
        node.next=n.next.next;
        return true;
    }

This works. But what if I want to delete the last node e? I know we can do this in c/c++ by manually freeing the space allocated but is it possible to do it in Java? I did try allocating a null to the value but that does not seem to work

if(node.next==null) {
        LinkedListNode dummynode=null;
        node=dummynode;
        return true;
    }

Solution

  • No, this is not possible. You really need a reference to the preceding node so you can update its next reference. A doubly linked list provides such a back reference, but when you are speaking of a singly linked list, the function must get a reference to the preceding node in some other way.

    I know we can do this in c/c++ by manually freeing the space allocated

    That would not be enough. In C/C++ you also need to set the previous node's next pointer to NULL/nullptr, or else you'll get undefined behaviour. The only thing you can do more in C++ is to pass the previous node's next pointer by reference.

    But no matter how you do it, the function must be able to access the next pointer/reference of the preceding node, or it will not be possible.