public class CircularLinkedList {
// Node class
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// Head of the linked list
Node head;
// Method to add a node to the end of the list
public void addLast(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
head.next = head;
} else {
Node current = head;
while (current.next != head) {
current = current.next;
}
current.next = newNode;
newNode.next = head;
}
}
// Method to count the number of nodes in the list
public int countNodes() {
if (head == null) {
return 0;
} else {
int count = 1;
Node current = head;
while (current.next != head) {
current = current.next;
count++;
}
return count;
}
}
public static void main(String[] args) {
CircularLinkedList list = new CircularLinkedList();
list.addLast(1);
list.addLast(2);
list.addLast(3);
list.addLast(4);
System.out.println("The circular linked list contains " + list.countNodes() + " nodes.");
}
}
The circular linked list contains 4 nodes.
Node
class to represent a node in the linked list. Each node contains an integer data
and a reference to the next node in the list. The CircularLinkedList
class contains a reference to the head of the list, a method to add a node to the end of the list, and a method to count the number of nodes in the list.addLast
method, a new node is created with the specified data. If the list is empty (i.e. the head is null
), the new node becomes the head of the list, and its next
field is set to itself, making it a circular list. Otherwise, the method traverses the list starting from the head, and finds the last node. The next
field of the last node is set to the new node, and the next
field of the new node is set to the head, making it a circular list.countNodes
method, the method checks if the list is empty (i.e. the head is null
). If it is, the method returns 0 to indicate that there are no nodes in the list. Otherwise, the method initializes a counter to 1 (since the head node is included in the count), and traverses the list starting from the head, counting each node along the way. The counter is returned when the end of the list is reached.main
method, the program creates a new CircularLinkedList
object, adds some nodes to the list, and counts the number of nodes in the list using the countNodes
method. The result is printed to the console.