└── Circular linkedlist traversal /Circular linkedlist traversal: -------------------------------------------------------------------------------- 1 | // Define the Node class 2 | class Node { 3 | int data; 4 | Node next; 5 | 6 | public Node(int data) { 7 | this.data = data; 8 | this.next = null; 9 | } 10 | } 11 | 12 | // Define the CircularLinkedList class 13 | class CircularLinkedList { 14 | private Node head; 15 | private Node tail; 16 | 17 | public CircularLinkedList() { 18 | head = null; 19 | tail = null; 20 | } 21 | 22 | // Method to add a node to the list 23 | public void addNode(int data) { 24 | Node newNode = new Node(data); 25 | if (head == null) { 26 | head = newNode; 27 | tail = newNode; 28 | newNode.next = head; 29 | } else { 30 | tail.next = newNode; 31 | tail = newNode; 32 | tail.next = head; 33 | } 34 | } 35 | 36 | // Method to traverse the list 37 | public void traverseList() { 38 | if (head != null) { 39 | Node current = head; 40 | do { 41 | System.out.print(current.data + " "); 42 | current = current.next; 43 | } while (current != head); 44 | } else { 45 | System.out.println("The list is empty."); 46 | } 47 | } 48 | 49 | public static void main(String[] args) { 50 | CircularLinkedList cll = new CircularLinkedList(); 51 | 52 | // Adding nodes to the list 53 | cll.addNode(1); 54 | cll.addNode(2); 55 | cll.addNode(3); 56 | cll.addNode(4); 57 | 58 | // Traversing the list 59 | cll.traverseList(); // Output: 1 2 3 4 60 | } 61 | } 62 | --------------------------------------------------------------------------------