1

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;
    }

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Okay, that explains a lot. Thanks🙂
1

If I understand your question correct, you can delete the last node by setting the .next attribute of the previous node to null. If your nodes contain the attribute .previous, you can use that. So

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

If you don't have a previous attribute, you need to check for each node if the next node will be the end node. So

if(node.next != null && node.next.next == null){
       node.next = null;
       return true;
}

I hope that answers your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.