Circular Linked list implementation in java

    Circular Linked list – A linked list which has a circular structure. Last pointer of the linked list points the head node again.

As usual this linked list also has a pointer and data.

Let us create a circular linked list in java.

Program implementation:

This implementation starts from class CirLinkedList.

  • It has a class ‘Node’ with two data members. One is integer data and another one is nxt_ptr.
  • Constructor initialises the data member’s value.
  • ‘insert()’ : This function inserts the data into the circular linked list.
  • ‘display()’: This function displays the circular linked list into the output screen.
  • ‘main()’ : It creates the object for the circular linked list and calls the member functions ‘insert()’ and ‘display()’.

Program:

class CirLinkedList {

    class Node {

        int data;

        Node nxt_ptr;

        Node(int data) {

            this.data = data;

            this.nxt_ptr = null;

        }

    }

    Node head;

    public void insert(int data) {

        Node newNode = new Node(data);

        if (head == null) {

            head = newNode;

            newNode.nxt_ptr = head;

        } else {

            Node temp = head;

            while (temp.nxt_ptr != head) {

                temp = temp.nxt_ptr;

            }

            temp.nxt_ptr = newNode;

            newNode.nxt_ptr = head;

        }

    }

    public void display() {

        if (head != null) {

            Node temp = head;

            do {

                System.out.print(temp.data + " -> ");

                temp = temp.nxt_ptr;

            } while (temp != head);

            System.out.println("(Points back to head)");

        }

    }

}

public class CircularLinkedListEg {

    public static void main(String[] args) {

        CirLinkedList cL1 = new CirLinkedList();

        // Insert the data elements to circular linked list

        cL1.insert(21);

        cL1.insert(56);

        cL1.insert(120);

        cL1.insert(234);

        cL1.insert(301);

        cL1.insert(67);

        // Display the circular linked list

        System.out.println("The data in the Circular Linked List are:");

        cL1.display();

    }

}

Output:

C:\raji\blog>javac CircularLinkedListEg.java

C:\raji\blog>java CircularLinkedListEg

The data in the Circular Linked List are:

21 -> 56 -> 120 -> 234 -> 301 -> 67 -> (Points back to head)

This is the implementation of Circular Linked list in java. Hope this code is useful to you. Keep coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.