'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 1:[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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | niklbird |
