Dijkstra’s algorithm implementation in java

 Dijkstra’s algorithm : It is a algorithm to find the shortest path between nodes in a graph. It deals with ‘graph’ data structure. It suits for both directed and undirected graph.

Usage:

GPS navigation, Pathfinding in AI and routing.

Logic:

  • Assign the starting node with distance 0 and remaining node as infinity.
  • Visit the nearest node(unvisited),find the shortest distance and mark it as visited.
  • Now, add the distance value.
  • In the same way, find the shortest route by visiting all nodes.
  • Finally, print the value.

Program:

import java.util.*;

class Graph {

    private int g_vertices;

    private List<List<Node>> l_adjList;

    static class Node implements Comparable<Node> {

        int g_vertex;

        int s_distance;

        Node(int g_vertex, int s_distance) {

            this.g_vertex = g_vertex;

            this.s_distance = s_distance;

        }

        @Override

        public int compareTo(Node other) {

            return Integer.compare(this.s_distance, other.s_distance);

        }

    }

    Graph(int g_vertices) {

        this.g_vertices = g_vertices;

        l_adjList = new ArrayList<>();

        for (int i = 0; i < g_vertices; i++) {

            l_adjList.add(new ArrayList<>());

        }

    }

    //Code for undirected graph

    void addEdge(int src, int dest, int weight) {

        l_adjList.get(src).add(new Node(dest, weight));

        l_adjList.get(dest).add(new Node(src, weight));

    }

    void dijkstra(int src) {

        PriorityQueue<Node> pq1 = new PriorityQueue<>();

        int[] distances = new int[g_vertices];

        Arrays.fill(distances, Integer.MAX_VALUE);

        distances[src] = 0;

        pq1.add(new Node(src, 0));

        while (!pq1.isEmpty()) {

            Node current = pq1.poll();

            int u = current.g_vertex;

            for (Node neighbor : l_adjList.get(u)) {

                int v = neighbor.g_vertex;

                int weight = neighbor.s_distance;

                if (distances[u] + weight < distances[v]) {

                    distances[v] = distances[u] + weight;

                    pq1.add(new Node(v, distances[v]));

                }

            }

        }

        System.out.println("Vertex \tSource Distance");

        for (int i = 0; i < g_vertices; i++) {

            System.out.println(i + "\t" + distances[i]);

        }

    }

}

public class DijkstraAlgorithmEg {

    public static void main(String[] args) {

        Graph g1 = new Graph(6);

        g1.addEdge(0, 1, 5);

        g1.addEdge(0, 2, 3);

        g1.addEdge(1, 3, 4);

        g1.addEdge(1, 4, 10);

        g1.addEdge(2, 5, 7);

        g1.addEdge(4, 3, 4);

        g1.addEdge(3, 5, 11);

        g1.dijkstra(0);

    }

}

Output:

C:\raji\blog>javac DijkstraAlgorithmEg.java

C:\raji\blog>java DijkstraAlgorithmEg

Vertex  Source Distance

0       0

1       5

2       3

3       9

4       13

5       10

Here, the implementation of Dijkstra algorithm in java was successful. Hope, this code is useful to you. Keep coding!!!

AVL Tree implementation in java

         AVL Tree -A special type of binary search tree which self balance itself. The condition is the difference between heights of left and right sub trees should be less than one for all nodes.

Program implementation:

It has the following steps to implement the program.

Input : Height and balance factor of a node.

Logic:

  • Read the height and balance factor.
  • Rotate the tree as right side.
  • Next, rotate it in the left side.
  • Insert the key value according to it.
  • There are four types to AVL balancing.
  • Left Left Case,Right Right Case, Left Right Case, Right Left Case.
  • Finally, call the inorder() function to print the tree by inorder traversal.

Java Implementation Of AVL Tree:

class AVL_Node {

    int key, ht;

    AVL_Node c_left, c_right;

    AVL_Node(int d) {

        key = d;

        ht = 1;

    }

}

class AVLTreeEg {

    AVL_Node root;

    int height(AVL_Node N) {

        return (N == null) ? 0 : N.ht;

    }

    int getBalance(AVL_Node N) {

        return (N == null) ? 0 : height(N.c_left) - height(N.c_right);

    }

    AVL_Node rightRotate(AVL_Node y) {

        AVL_Node x = y.c_left;

        AVL_Node T2 = x.c_right;

        x.c_right = y;

        y.c_left = T2;

        y.ht = Math.max(height(y.c_left), height(y.c_right)) + 1;

        x.ht = Math.max(height(x.c_left), height(x.c_right)) + 1;

        return x;

    }

    AVL_Node leftRotate(AVL_Node x) {

        AVL_Node y = x.c_right;

        AVL_Node T2 = y.c_left;

        y.c_left = x;

        x.c_right = T2;

        x.ht = Math.max(height(x.c_left), height(x.c_right)) + 1;

        y.ht = Math.max(height(y.c_left), height(y.c_right)) + 1;

        return y;

    }

    AVL_Node insert(AVL_Node node, int key) {

        if (node == null)

            return new AVL_Node(key);

        if (key < node.key)

            node.c_left = insert(node.c_left, key);

        else if (key > node.key)

            node.c_right = insert(node.c_right, key);

        else

            return node;

        node.ht = 1 + Math.max(height(node.c_left), height(node.c_right));

        int balance = getBalance(node);

        if (balance > 1 && key < node.c_left.key)

            return rightRotate(node);

        if (balance < -1 && key > node.c_right.key)

            return leftRotate(node); 

        if (balance > 1 && key > node.c_left.key) {

            node.c_left = leftRotate(node.c_left);

            return rightRotate(node);

        } 

        if (balance < -1 && key < node.c_right.key) {

            node.c_right = rightRotate(node.c_right);

            return leftRotate(node);

        }

        return node;

    }

    void inOrder(AVL_Node node) {

        if (node != null) {

            inOrder(node.c_left);

            System.out.print(node.key + " ");

            inOrder(node.c_right);

        }

    }

    public static void main(String[] args) {

        AVLTreeEg t1 = new AVLTreeEg();

        t1.root = t1.insert(t1.root, 110);

        t1.root = t1.insert(t1.root, 201);

        t1.root = t1.insert(t1.root, 320);

        t1.root = t1.insert(t1.root, 140);

        t1.root = t1.insert(t1.root, 530);

        t1.root = t1.insert(t1.root, 250);

        System.out.println("Inorder traversal of AVL tree is given below:");

        t1.inOrder(t1.root);

    }

}

Output:

C:\raji\blog>javac AVLTreeEg.java

C:\raji\blog>java AVLTreeEg

Inorder traversal of AVL tree is given below:

110 140 201 250 320 530

This is the way to implement AVL Tree in java. Keep coding!!!!!

How to implement Java Program to find the height of a Binary Tree?

              Binary tree is always having two nodes. The height of the binary tree is nothing but the levels of the binary tree.

Let us implement this concept in java.

How it Works?

  • ·       Create a binary tree with Node. This Node has a integer data and left child and right child.
  • ·       Initialise the values.
  • ·       Create a binary tree using a class.
  • ·       It has root node.
  • ·       Member Functions are insert(), FindItHeight().
  • ·       ‘main()’ function creates the object for binary tree.
  • ·       Using Scanner class, inputs read from the user.
  • ·       The member functions are called for finding the height.
  • ·       Finally,the height value is displayed in the output screen.

Program:

import java.util.Scanner;

class Node {

    int b_data;

    Node c_left, c_right;

    public Node(int item) {

        b_data = item;

        c_left = c_right = null;

    }

}

class BTreeEg {

    Node root;

    Node insert(Node node, int b_data) {

        if (node == null) {

            return new Node(b_data);

        }

        Scanner s1 = new Scanner(System.in);

        System.out.println("Please Enter 1 to insert left of binary tree " + node.b_data + ", 2 to insert right of the binary tree:");

        int usr_choice = s1.nextInt();

        if (usr_choice == 1) {

            node.c_left = insert(node.c_left, b_data);

        } else {

            node.c_right = insert(node.c_right, b_data);

        }

        return node;

    }

    int findItHeight(Node node) {

        if (node == null)

            return -1; // It means Tree is empty

        int lHeight = findItHeight(node.c_left);

        int rHeight = findItHeight(node.c_right);

        return Math.max(lHeight, rHeight) + 1;

    }

    public static void main(String[] args) {

        Scanner s1 = new Scanner(System.in);

        BTreeEg bt = new BTreeEg();

        System.out.println("Enter the root node value:");

        int root_Value = s1.nextInt();

        bt.root = new Node(root_Value);

        System.out.println("Enter number of the nodes to insert in the binary tree:");

        int n = s1.nextInt();

        for (int i = 0; i < n; i++) {

            System.out.println("Enter the value for node:");

            int value = s1.nextInt();

            bt.insert(bt.root, value);

        }

        System.out.println("Height of the tree is : " + bt.findItHeight(bt.root));

        s1.close();

    }

}

Output:

C:\raji\blog>java BTreeEg

Enter the root node value:

56

Enter number of the nodes to insert in the binary tree:

4

Enter the value for node:

23

Please Enter 1 to insert left of binary tree 56, 2 to insert right of the binary tree:

1

Enter the value for node:

12

Please Enter 1 to insert left of binary tree 56, 2 to insert right of the binary tree:

2

Enter the value for node:

67

Please Enter 1 to insert left of binary tree 56, 2 to insert right of the binary tree:

1

Please Enter 1 to insert left of binary tree 23, 2 to insert right of the binary tree:

15

Enter the value for node:

45

Please Enter 1 to insert left of binary tree 56, 2 to insert right of the binary tree:

1

Please Enter 1 to insert left of binary tree 23, 2 to insert right of the binary tree:

19

Please Enter 1 to insert left of binary tree 67, 2 to insert right of the binary tree:

1

Height of the tree is : 3

This is the way of creating java program to find the length of binary tree. Hope this code is useful to you. Keep Coding!!!

Java Program to check the Binary tree is balanced or not

    A binary tree has exactly two nodes for each parent node. Sometimes, sub parent has less than two nodes or no nodes at all. For this type of binary trees, we check the tree balance.

Logic:

  • ·       A tree is created with left and right child with data.
  • ·       Right side height is calculated.
  • ·       Left side height is calculated.
  • ·       Check the balance.
  • ·       If both are equal, then the binary tree is balanced. Otherwise, it is not balanced.

 Let us implement this in java.

Program implementation:

  • A tree structure is created with integer data, left and right child.
  • A constructor is used to initialise the value.
  • A public class is created with three member function.
  • ‘balanceIt()’ – it checks the balance of tree.
  • ‘checkHeight()’ -it finds the height of given tree.
  • ‘main()’ – As usual, this function creates the object for the public class.
  • It reads the tree values.
  • Calls the ‘balanceIt()’ function to get the balanced tree value.

Program:

class Tree_Node {

    int data;

    Tree_Node left;

    Tree_Node right;

 

    Tree_Node(int x) {

        data = x;

    }

}

 

public class BalancedBinaryTreeEg {

 

    public boolean balancedIt(Tree_Node root) {

        return checkHeight(root) != -1;

    }

 

    private int checkHeight(Tree_Node node) {

        if (node == null) {

            return 0;

        }

 

        int leftHeight = checkHeight(node.left);

        if (leftHeight == -1) return -1;

 

        int rightHeight = checkHeight(node.right);

        if (rightHeight == -1) return -1;

 

        if (Math.abs(leftHeight - rightHeight) > 1) {

            return -1; // it means tree is not balanced

        }

 

        return Math.max(leftHeight, rightHeight) + 1;

    }

 

    public static void main(String[] args) {

        BalancedBinaryTreeEg t1 = new BalancedBinaryTreeEg();

        boolean check;

        Tree_Node root = new Tree_Node(1);

        root.left = new Tree_Node(2);

        root.right = new Tree_Node(3);

        root.left.left = new Tree_Node(4);

        root.left.right = new Tree_Node(5);

        root.left.left.left = new Tree_Node(8);

        check = t1.balancedIt(root);

        if(check)

        {

         System.out.println("The binary tree is balanced");

          }

        else

        {

         System.out.println("The Binary tree is not balanced");

        }

    }

}

Output:

Just compile and execute the program to get the output.

C:\raji\blog>javac BalancedBinaryTreeEg.java

C:\raji\blog>java BalancedBinaryTreeEg

The Binary tree is not balanced

This is the way to check the given binary tree is balanced or not in java. Hope, this code is useful to you. Keep coding!!! 

Thread Synchronization in java

              Thread is a lightweight process under execution. As java supports multithreading, thread synchronization is needed. It provides consistency. It also avoids thread interference.

Let us start the implementation.

Program implementation:

  • Class: SharedResource, ThreadSynchronizationEg ,WorkerThread ( derived from Thread).
  • Member variables: c( counting purpose), resrc ( object of SharedResource)
  • Member functions:
  •    ‘increment()’ -used to increment the count(c) value.
  •   ‘getCount()’ -gets the count (c)value.
  • Overridden ‘run()’ – runs the thread.
  • ‘main()’ 
  • It creates the object for SharedResource class.
  • Threads are created and shared common resources.
  • Thread process is started for both threads.
  • They join the shared regions. Based on wait time, it is executed.
  • Finally, the count value is printed.    

Program:

class SharedResource {

    private int c = 0;

    // Thread safety purpose, this method is used

    public synchronized void increment() {

        c++;

        System.out.println(Thread.currentThread().getName() + " count(incremented) is: " + c);

    }

    public int getCount() {

        return c;

    }

}

class WorkerThread extends Thread {

    private SharedResource resrc;

    public WorkerThread(SharedResource resrc) {

        this.resrc = resrc;

    }

 

    @Override

    public void run() {

        for (int i = 0; i < 5; i++) {

            resrc.increment();

            try {

                Thread.sleep(50);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

        }

    }

}

public class ThreadSynchronizationEg {

    public static void main(String[] args) {

        SharedResource resrc = new SharedResource();

        // Create multiple threads sharing the same resource

        Thread t1 = new WorkerThread(resrc);

        Thread t2 = new WorkerThread(resrc);

        t1.start();

        t2.start();

        try {

            t1.join();

            t2.join();

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        System.out.println("The final count is: " + resrc.getCount());

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac ThreadSynchronizationEg.java

C:\raji\blog>java ThreadSynchronizationEg

Thread-1 count(incremented) is: 1

Thread-0 count(incremented) is: 2

Thread-1 count(incremented) is: 3

Thread-0 count(incremented) is: 4

Thread-1 count(incremented) is: 5

Thread-0 count(incremented) is: 6

Thread-1 count(incremented) is: 7

Thread-0 count(incremented) is: 8

Thread-1 count(incremented) is: 9

Thread-0 count(incremented) is: 10

The final count is: 10

That’s the way of implementing thread synchronization in java. Hope this code is easy to understand .Happy Coding!!!

Java Program to Count the number of nodes in a binary tree

     Binary tree is a data structure which a root and nodes. Here, a root is like a parent. Nodes are like children. It has a structure of root, left child and right child.

Let us count the number of nodes in a binary tree. Binary tree has two nodes in all levels.

Program implementation:

  • ·       Create a node with data and left child and right child.
  • ·       Initialise the values.
  • ·       Create a binary tree class. Declare a variable for root.
  • ·       A function is defined to count the nodes.
  • ·       Using a recursive function, count it.
  • ·       Let us invoke the main() function, to initialise the objects.
  • ·       Use the objects to call the function.
  • ·       Print the number of nodes in the output screen.

Classes incuded:

Node: It defines the structureof node.

BinaryTreeEg : It defines the structure of binary tree.

Variables:

‘data’ , ‘value’, ‘c_left’,’c_right’

Functions:

‘countIt()’ – This function counts the number of nodes.

‘main()’ – It creates the objects and calls the function to get the output.

Program:

class Node {

    int data;

    Node c_left, c_right;

    Node(int value) {

        data = value;

       c_left = c_right = null;

    }

}

class BinaryTreeEg {

    Node root;

    // countIt method to count the nodes in the binary tree

    public int countIt(Node node) {

        if (node == null) {

            return 0;

        }

        // A recursive function to count the nodes

        return 1 + countIt(node.c_left) + countIt(node.c_right);

    }

    public static void main(String[] args) {

        BinaryTreeEg bt = new BinaryTreeEg();

        // Creating a sample binary tree

        bt.root = new Node(10);

        bt.root.c_left = new Node(20);

        bt.root.c_right = new Node(30);

        bt.root.c_left.c_left = new Node(40);

        bt.root.c_left.c_right = new Node(50);

        bt.root.c_right.c_left = new Node(60);

        bt.root.c_right.c_right = new Node(70);

        System.out.println("Number of nodes in the binary tree: " + bt.countIt(bt.root));

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac BinaryTreeEg.java

C:\raji\blog>java BinaryTreeEg

Number of nodes in the binary tree: 7

That’s all. The java program to count the number of nodes in a binary tree was implemented successfully. Hope this code is useful to you. Happy coding!!

LRU cache mechanism implementation in java

     LRU -Least Recently used. Cache is a fast memory. Let us implement the LRU cache mechanism in java.

Data structures used: hashmap and doubly linked list.

Program implementation:

  • A class LRUCacheEg is created with three variables capa(capacity), hash map object and doubly Linked list.
  • Constructor initialises the three variable.
  •  ‘get()’ function is used to get the value.
  • ‘put()’ function is use to return value.
  • ‘Node’ and ‘doubly linked list’ are created with its structure.
  • ‘addtoHead()’ , ‘remove tail()’, ‘removenode()’ and ‘removetohead()’ are the functions in the class.
  • Create the main() function. Create cache object and call the get and put function to display the output.

Program:

import java.util.*;

class LRUCacheEg<K, V> {

    private final int capa;

    private final Map<K, Node<K, V>> cache;

    private final DoublyLinkedList<K, V> list;

    public LRUCacheEg(int capa) {

        this.capa = capa;

        this.cache = new HashMap<>();

        this.list = new DoublyLinkedList<>();

    }

    public V get(K key) {

        if (!cache.containsKey(key)) {

            return null; // if Key is not present,return null.

        }

        Node<K, V> node = cache.get(key);

        list.moveToHead(node); // Update access order

        return node.value;

    }

    public void put(K key, V value) {

        if (cache.containsKey(key)) {

            Node<K, V> node = cache.get(key);

            node.value = value;

            list.moveToHead(node);

        } else {

            if (cache.size() == capa) {

                Node<K, V> tail = list.removeTail();

                cache.remove(tail.key);

            }

            Node<K, V> newNode = new Node<>(key, value);

            list.addToHead(newNode);

            cache.put(key, newNode);

        }

    }

    private static class Node<K, V> {

        K key;

        V value;

        Node<K, V> prev;

        Node<K, V> next;

 

        Node(K key, V value) {

            this.key = key;

            this.value = value;

        }

    }

    private static class DoublyLinkedList<K, V> {

        private final Node<K, V> head;

        private final Node<K, V> tail;

        DoublyLinkedList() {

            head = new Node<>(null, null);

            tail = new Node<>(null, null);

            head.next = tail;

            tail.prev = head;

        }

        void addToHead(Node<K, V> node) {

            node.next = head.next;

            node.prev = head;

            head.next.prev = node;

            head.next = node;

        }

        void moveToHead(Node<K, V> node) {

            removeNode(node);

            addToHead(node);

        }

        Node<K, V> removeTail() {

            if (tail.prev == head) return null; // List is empty

            Node<K, V> node = tail.prev;

            removeNode(node);

            return node;

        }

        private void removeNode(Node<K, V> node) {

            node.prev.next = node.next;

            node.next.prev = node.prev;

        }

    }

    public static void main(String[] args) {

        LRUCacheEg<Integer, String> c1 = new LRUCacheEg<>(3);

        c1.put(1, "One");

        c1.put(2, "Two");

        c1.put(3, "Three");

        System.out.println(c1.get(2));

        c1.put(4, "Four");

        System.out.println(c1.get(3));

    }

}

Output:

C:\raji\blog>javac LRUCacheEg.java

C:\raji\blog>java LRUCacheEg

Two

Three

This is the sample implementation of LRU cache mechanism in java. Hope,this code is useful to you.Keep coding!!!

Implementation of Binary Search Tree and its operations:

           Binary Search Tree is a special one in which the nodes are organised in sorted order.

It has following functions to implement.

  • ‘Node creation’ -  Creates the structure of node
  • ‘Class creation’ -class and its member functions are created.
  • ‘Constrctor()’- initialises the values.
  • ‘insert()’- add the node to the binary tree
  • ‘insertRec()’ - add the elements to the tree.
  • ‘inorder()’ -inorder traversal of node.
  • ‘inorderRec()’ -inorder traversal of data.
  • ‘search()’ -search the binary tree nodes
  • ‘searchRec()’ – search the elements.
  • ‘main()’ -it creates the object for class. It adds the elements, traverse the tree in inorder and find a key value.

Program:

import java.util.Scanner;

class Node {

    int key;

    Node l_value, r_value;

    public Node(int item) {

        key = item;

        l_value = r_value = null;

    }

}

class BinarySearchTreeEg {

    Node root;

     // Constructor to initialise values

    BinarySearchTreeEg() {

        root = null;

    }

     // Add a new key value

    void insert(int key) {

        root = insertRec(root, key);

    }

     // To insert a key using recursive function

    Node insertRec(Node root, int key) {

        if (root == null) {

            root = new Node(key);

            return root;

        }

        if (key < root.key) {

            root.l_value = insertRec(root.l_value, key);

        } else if (key > root.key) {

            root.r_value = insertRec(root.r_value, key);

        }

        return root;

    }

     // Let us do In-order traversal

    void inorder() {

        inorderRec(root);

    }

     void inorderRec(Node root) {

        if (root != null) {

            inorderRec(root.l_value);

            System.out.print(root.key + " ");

            inorderRec(root.r_value);

        }

    }

     // let us search the key

    boolean search(int key) {

        return searchRec(root, key);

    }

     boolean searchRec(Node root, int key) {

        if (root == null) {

            return false;

        }

        if (root.key == key) {

            return true;

        }

        return key < root.key ? searchRec(root.l_value, key) : searchRec(root.r_value, key);

    }

     public static void main(String[] args) {

        BinarySearchTreeEg bsteg = new BinarySearchTreeEg();

 

        // add the elements to the binary Search Tree

        bsteg.insert(510);

        bsteg.insert(230);

        bsteg.insert(40);

        bsteg.insert(27);

        bsteg.insert(675);

        bsteg.insert(120);

        bsteg.insert(9);

         // display the In-order traversal

        System.out.println("Inorder traversal:");

        bsteg.inorder();

        //Search the key element

        Scanner s1 = new Scanner(System.in);

        System.out.println("\n"+"Enter the key value to search:");

        int a =s1.nextInt();

        if(bsteg.search(a))

          System.out.println("The key is available");

        else

          System.out.println("The key is not available");

        s1.close();       

    }

}

Output:

C:\raji\blog>javac BinarySearchTreeEg.java

C:\raji\blog>java BinarySearchTreeEg

Inorder traversal:

9 27 40 120 230 510 675

Enter the key value to search:

230

The key is available

C:\raji\blog>java BinarySearchTreeEg

Inorder traversal:

9 27 40 120 230 510 675

Enter the key value to search:

234

The key is not available

This is way of implementing Binary search Tree and its operations. Hope you learnt the Binary Search Tree. Keep coding.

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!!!!