Count Number of Nodes in Linked List

Count number of nodes in linked list. In this program to print and count the number of nodes present in the element. In this program it will read the element in the nodes in java

public class Main 
{
class Node
{
int data;
Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
public Node head = null;
public Node tail = null;
public void addNode(int data)
{
Node newNode = new Node(data);
if(head == null)
{
head = newNode;
tail = newNode;
}
else
{
tail.next = newNode;
tail = newNode;
}
}
public int Main()
{
int count = 0;
Node current = head;
while(current != null)
{
count++;
current = current.next;
}
return count;
}
public void display()
{
Node current = head;
if(head == null)
{
System.out.println("List is empty");
return;
}
System.out.println("nodes of singly linked list");
while(current != null)
{
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}

public static void main(String[] args)
{
Main sList = new Main();
sList.addNode(2);
sList.addNode(4);
sList.addNode(6);
sList.addNode(8);
sList.addNode(10);
sList.display();
System.out.println("count of nodes present in the list" + sList.Main());
}
}

 

Output:

nodes of singly linked list
2 4 6 8 10
count of nodes present in the list5

Linked List in Java

In Java, a linked list is a dynamic data structure whose size grows as you add entries to the list and shrinks as you remove them. Containers are used to store the linked list’s elements. The initial container’s link is kept in the list. A link to the next container in the list may be found on every container.

How Linked List is Implement in Java

This class implements the LinkedList data structure, which is a linear data structure in which the components are not stored in sequential order and each element is a separate object having a data and address part. Pointers and addresses are used to connect the elements.

List in Java Program

A list interface in Java is an ordered collection of objects that can store duplicate data. Because a List keeps the insertion order, it enables both positional access and element insertion. The List interface is used to keep track of the collection’s order. It is a Collection’s child interface. It’s a sorted collection of objects that can store duplicate values. List supports positional access and insertion of members because the insertion order is preserved.

While Loop to Execute Count Number of Nodes in Linked List

When we need to run a block of statements repeatedly in Java, we utilise loops. The while loop in Java is a control flow statement that allows code to be repeated based on a Boolean condition. The while loop is similar to a looping if statement.