Java Program to Insert a Node at the End of a Linked List

Introduction

Inserting a node at the end of a linked list involves adding a new node after the current last node, then updating the last node’s next pointer to point to the new node. This operation is commonly used when you need to append data to the end of the list. This guide will walk you through writing a Java program that inserts a node at the end of a singly linked list.

Problem Statement

Create a Java program that:

  • Implements a singly linked list.
  • Inserts a node at the end of the linked list.
  • Displays the linked list before and after the insertion.

Example:

  • Input: Linked list: 1 -> 2 -> 3 -> 4, insert node with value 5

  • Output: 1 -> 2 -> 3 -> 4 -> 5

  • Input: Linked list: 10 -> 20 -> 30, insert node with value 40

  • Output: 10 -> 20 -> 30 -> 40

Solution Steps

  1. Create the Linked List and Node Structure: Define a Node class to represent each element in the linked list and a LinkedList class to manage the list.
  2. Add Nodes to the Linked List: Implement methods to add nodes to the linked list.
  3. Insert a Node at the End of the Linked List:
  • Create a new node with the specified value.
  • Traverse the linked list to find the last node.
  • Set the last node’s next pointer to the new node.
  1. Display the Result: Output the linked list before and after inserting the new node.

Java Program

// Java Program to Insert a Node at the End of a Linked List
// Author: https://www.rameshfadatare.com/

class Node {
    int data;
    Node next;

    // Constructor to initialize the node
    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}

class LinkedList {
    Node head;

    // Method to add a new node at the end of the list
    public void insertAtEnd(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            // Step 1: If the list is empty, initialize the head with the new node
            head = newNode;
        } else {
            // Step 2: Traverse to the end of the list
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            // Step 3: Set the next of the last node to the new node
            current.next = newNode;
        }
    }

    // Method to display the linked list
    public void display() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " -> ");
            current = current.next;
        }
        System.out.println("null");
    }
}

public class InsertAtEnd {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();

        // Adding elements to the linked list
        list.insertAtEnd(1);
        list.insertAtEnd(2);
        list.insertAtEnd(3);
        list.insertAtEnd(4);

        System.out.println("Original Linked List:");
        list.display();

        // Inserting a node at the end of the linked list
        list.insertAtEnd(5);

        System.out.println("Linked List after inserting node with value 5 at the end:");
        list.display();
    }
}

Explanation

Step 1: Initialize the Node Class

  • The Node class represents a single node in the linked list. Each node contains data and a reference to the next node in the list.
  • The constructor initializes the node with data and sets the next pointer to null.

Step 2: Initialize the LinkedList Class

  • The LinkedList class manages the linked list. The class contains the head node that points to the first node in the list.
  • The insertAtEnd() method appends a new node to the end of the list:
    • If the list is empty (head is null), the head is set to the new node.
    • Otherwise, the list is traversed to find the last node, and the next pointer of the last node is updated to point to the new node.

Output Example

Original Linked List:
1 -> 2 -> 3 -> 4 -> null
Linked List after inserting node with value 5 at the end:
1 -> 2 -> 3 -> 4 -> 5 -> null

Example with Different Input

If you modify the input list to:

list.insertAtEnd(10);
list.insertAtEnd(20);
list.insertAtEnd(30);

And insert the node with value 40 at the end:

list.insertAtEnd(40);

The output will be:

Original Linked List:
10 -> 20 -> 30 -> null
Linked List after inserting node with value 40 at the end:
10 -> 20 -> 30 -> 40 -> null

Conclusion

This Java program demonstrates how to insert a node at the end of a singly linked list by traversing to the last node and updating its next pointer. The program efficiently adds the node to the end of the list, providing a fundamental operation that is useful in various scenarios. This exercise is valuable for understanding how to manage and manipulate linked lists in Java programming.

Leave a Comment

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

Scroll to Top