Google News
logo
Java program to create and display a Circular Linked List
In the following example of Java program to create and display a circular linked list :
Program :
public class CircularLinkedList {
    
    // 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 addLast(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
            head.next = head;
        } else {
            Node current = head;
            while (current.next != head) {
                current = current.next;
            }
            current.next = newNode;
            newNode.next = head;
        }
    }
    
    // Method to display the list
    public void display() {
        if (head == null) {
            System.out.println("The list is empty");
        } else {
            Node current = head;
            do {
                System.out.print(current.data + " ");
                current = current.next;
            } while (current != head);
        }
    }
    
    public static void main(String[] args) {
        CircularLinkedList list = new CircularLinkedList();
        list.addLast(1);
        list.addLast(2);
        list.addLast(3);
        list.addLast(4);
        System.out.println("The circular linked list:");
        list.display();
    }
    
}
Output :
The circular linked list:1 2 3 4 
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 CircularLinkedList class contains a reference to the head of the list, a method to add a node to the end of the list, and a method to display the list.

In the addLast method, a new node is created with the specified data. If the list is empty (i.e. the head is null), the new node becomes the head of the list, and its next field is set to itself, making it a circular list. Otherwise, the method traverses the list starting from the head, and finds the last node. The next field of the last node is set to the new node, and the next field of the new node is set to the head, making it a circular list.

In the display method, the method checks if the list is empty (i.e. the head is null). If it is, the method prints a message indicating that the list is empty. Otherwise, the method traverses the list starting from the head, and prints the data of each node. The method uses a do-while loop to ensure that the list is printed at least once, even if it contains only one node.

In the main method, the program creates a new CircularLinkedList object, adds some nodes to the list, and displays the list.