CircularLinkedList

CircularLinkedList

 
In singly and doubly linked lists the end of the lists are indicated with NULL value.  But circular linked list doesn’t have any ends. End of the circular linked list points to the head of the list. So, there is no node with Null.
 
A simple circular linked list class and iterating over circular list.
 
Here is the code
 



package com.diaryreaders.datastructures.linkedlist;
public class CircularLinkedList {
private CircularLinkedList next;
private int data;
public CircularLinkedList getNext() {
return next;
}
public void setNext(CircularLinkedList next) {
this.next = next;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public static void main(String[] args) {
CircularLinkedList cll1 = new CircularLinkedList();
CircularLinkedList cll2 = new CircularLinkedList();
CircularLinkedList cll3 = new CircularLinkedList();
CircularLinkedList cll4 = new CircularLinkedList();
CircularLinkedList cll5 = new CircularLinkedList();
cll1.setData(1);
cll2.setData(2);
cll3.setData(3);
cll4.setData(4);
cll5.setData(5);
cll1.setNext(cll2);
cll2.setNext(cll3);
cll3.setNext(cll4);
cll4.setNext(cll5);
cll5.setNext(cll1); //circular end points to head
iterate(cll1);
}
private static void iterate(CircularLinkedList head) {
CircularLinkedList cll = head;
while (cll != null) {
System.out.println(cll.getData());
cll = cll.getNext();
if (head == cll) {
break;
}
}
}
}


 
Output:

 

No Comments Yet

Leave a Reply

Your email address will not be published.

Lorem ipsum dolor sit amet, consectetur a dipiscing elit. Vivamus leo ante,

FOLLOW US ON