Circular Linked Lists Traversal
Circular Linked List is a kind of Linked List in such a manner that it forms a circle. In the Circular Linked List, the last node points to the first node and there are no nodes available in the Circular Linked List which is having null at the address space. Thus in the Circular Linked List, the traversal terminated when we are at back at the first node again.
Both The Singly Linked List and Doubly Linked List can be created into a Circular List.
Below is the code for the Circular Linked List Traversal.
[code language=”css”]
public class CircularLinkedListTraversal {
public int size =0;
public Node head=null;
public Node tail=null;
//adding a new node at the start of the Cicular linked list
public void addNodeAtStart(int num){
System.out.println("Node " + num + " has been added at start");
Node n = new Node(num);
if(size==0){
head = n;
tail = n;
n.next = head;
}else{
Node temp = head;
n.next = temp;
head = n;
tail.next = head;
}
size++;
}
public int elementAt(int index){
if(index>size){
return -1;
}
Node n = head;
while(index-1!=0){
n=n.next;
index–;
}
return n.num;
}
//print the linked list
public void print(){
System.out.print("Circular Linked List:");
Node temp = head;
if(size<=0){
System.out.print("List is empty");
}else{
do {
System.out.print(" " + temp.num);
temp = temp.next;
}
while(temp!=head);
}
System.out.println();
}
//get Size of the Linked List
public int getSize(){
return size;
}
public static void main(String[] args) {
CircularLinkedListTraversal c = new CircularLinkedListTraversal();
c.addNodeAtStart(3);
c.addNodeAtStart(2);
c.addNodeAtStart(1);
c.print();
System.out.println("Size of linked list: "+ c.getSize());
}
}
class Node{
int num;
Node next;
public Node(int num){
this.num = num;
}
}
[/code]
OutPut:


Login/Signup to comment