How to remove the last node from a Singly Linked List in Java

By | June 21, 2020

In this post, We will learn How to remove the last node from a Singly Linked List in Java?

Program Logic to Remove/Delete Last node from Singly Linked List:

If we want to delete the last node of a linked list then find the second last node and make the next pointer of that node null.

Node<T> lastNode = head;
Node<T> previousToLastNode = null;
while(lastNode.next != null) {
previousToLastNode = lastNode;
lastNode = lastNode.next;
}
previousToLastNode.next = null;

Complete Source Code:

Output Of Above Program :

Original LinkedList:
10 20 30 40 50 60
After removing last Element:60
10 20 30 40 50

You May Also Like:

How to remove the first node from a Singly Linked List in Java ?
How to find Nth node from the end of a Singly Linked List in Java?
How to insert a node in Linked List at a given position in Java ?

That’s all about the How to remove the last node from a Singly Linked List in Java?
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *