Google News
logo
Java Program to create and display a Singly Linked List
In the following example of Java program to create and display a singly linked list :
Program :
public class SinglyLinkedList {
    
    // Node class
    static class Node {
        int data;
        Node next;
        
        Node(int data) {
            this.data = data;
            this.next = null;
        }
    }
    
    // Head of the linked list
    Node head;
    
    // Method to add a node to the end of the list
    public void add(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }
    
    // Method to display the list
    public void display() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
    }
    
    public static void main(String[] args) {
        SinglyLinkedList list = new SinglyLinkedList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.display();
    }
}
Output :
1 2 3 4 5 
The above program defines a Node class to represent a node in the linked list. Each node contains an integer data and a reference to the next node in the list. The SinglyLinkedList class contains a reference to the head of the list, and methods to add nodes to the end of the list and display the list.

In the add method, a new node is created with the specified data, and added to the end of the list. If the list is empty, the new node becomes the head. If the list is not empty, the method traverses the list until it reaches the last node, and adds the new node as its next node.

In the display method, the list is traversed from the head node to the end, and each node's data value is printed to the console.

In the main method, a new linked list is created, nodes are added to the list, and the list is displayed.