Insertion at the Last Position in Singly Linked List in JAVA

Insertion at Last Position in Singly Linked List in JAVA

A Singly Linked List is a type of Data Structure which stores data of homogeneous type in a list along with the address reference to the adjacent node of Data. In this page we’ll learn the Insertion at the Last Position in Singly Linked List in JAVA. To insert an element in the last of a linked list we’ll have to store the address reference of the new node in the previously last node and we’ll have to store the address reference of null with the new last node.


In the process of Insertion at the Last Position we’ll begin by checking whether if the linked list is empty.

 If the head is equal to null, then the list is already empty else the list already has an element.

In Order to insert a node in the end we’ll first store the current pointer address of null from the current last node to a temporary variable.

The value of that temporary variable will now be stored in the address of the new node being inserted.

Followed by which we’ll store the address of the new node into the previous last node of the linked list.

Below is the Algorithm that will help us to understand more about the insertion program.

Algorithm for Insertion in Singly Linked List in JAVA

  • ELSE
  • PTR = NULL
  • NEW -> NEXT = NULL
  • EXIT
Insertion in the end in a Linked List

Code in JAVA Language

import java.util.*;
public class Main 
    public static void main(String[] args) throws Exception {
        LinkedList ll = new LinkedList();
class LinkedList {
    private class Node {
        int data;
        Node next;
        // Node constructor
        // There are two fields in the node- data and address of next node
        public Node(int data, Node next) {
   = data;
   = next;
    private Node head;
    private Node tail;
    private int size;
    // Linked list constructor
    public LinkedList() {
            this.head = null;
            this.tail = null;
            this.size = 0;
    // Function to find the size of linked list
    public int size() {
            return this.size;
    // Function to traverse and print the linked list
    public void display() {
        Node temp = head;
        while (temp != null) {
            System.out.print( + "–>");
            // Set temp to point to the next node
            temp =;
    // Function to add a node at last of linked list
    public void addLast(int item) {
        // Create a temp node which does not point to any node
        Node temp = new Node(item, null);
        // If linked list is empty, temp is the head and tail node both
        if (this.size() == 0) {
            this.head = this.tail = temp;
        // else change next of tail such that it points to temp
        // and now the new tail is temp
        else {
   = temp;
            this.tail = temp;