In this tutorial, we will count the number of nodes in a given linked list.
Example – Program to find the length of the linked using Iterative way
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
public class LinkedList {
Node head;
public void addData(int new_data) {
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
public int getCountNodes() {
Node node = head;
int count = 0;
while (node != null) {
count++;
node = node.next;
}
return count;
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addData(1);
list.addData(2);
list.addData(3);
list.addData(4);
list.addData(5);
System.out.println("Count of LinkedList is " + list.getCountNodes());
}
}
Output
Count of LinkedList is 5
Example – Using Recursive way
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
public class LinkedList {
Node head;
public void addData(int new_data) {
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
public int getCountNodesUsingRecursive(Node node) {
if (node == null)
return 0;
return 1 + getCountNodesUsingRecursive(node.next);
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addData(1);
list.addData(2);
list.addData(3);
list.addData(4);
list.addData(5);
System.out.println("Count of LinkedList is " + list.getCountNodesUsingRecursive(list.head));
}
}
Output
Count of LinkedList is 5