-
Notifications
You must be signed in to change notification settings - Fork 110
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a1249ab
commit 0973634
Showing
1 changed file
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |