Count Linked List Element in Java

Write a java program to count the linked list element in the nodes. 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

What is 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 the 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.