Skip to content

Commit

Permalink
Create CircularLinkedList.java
Browse files Browse the repository at this point in the history
  • Loading branch information
kashish-51 authored Oct 15, 2023
1 parent a1249ab commit 0973634
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions Linkedlist/CircularLinkedList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
public class CircularLinkedList {
// It represents the node of list.
public class Node{
int data;
Node next;
public Node(int data) {
this.data = data;
}
}

//Declared head and tail pointer as null
public Node head = null;
public Node tail = null;

//with this function new node will be added at the end
public void add(int data){
//Create new node
Node newNode = new Node(data);
//Checks if the list is empty.
if(head == null) {
//If list is empty, both head and tail would point to new node.
head = newNode;
tail = newNode;
newNode.next = head;
}
else {
//tail will point to new node.
tail.next = newNode;
//New node will become new tail.
tail = newNode;
//Since, it is circular linked list tail will point to head.
tail.next = head;
}
}

//Displays all the nodes in the list
public void display() {
Node current = head;
if(head == null) {
System.out.println("List is empty");
}
else {
System.out.println("Nodes of the circular linked list are : ");
do{
//Prints each node by incrementing pointer.
System.out.print(" "+ current.data);
current = current.next;
}while(current != head);
System.out.println();
}
}

public static void main(String[] args) {
CreateList cl = new CreateList();
//Adds data to the list
cl.add(9);
cl.add(3);
cl.add(8);
cl.add(5);
//Displays all the nodes present in the list
cl.display();
}
}

0 comments on commit 0973634

Please sign in to comment.