In this article, we are going to see how we can create and count nodes in a singly linked list by using Java programming language.
Java Program to Create and Count Nodes in a Singly Linked List
Each element in linkedlist is called as a node. Here we need to first create nodes and then count the number of nodes. To create nodes we need to add elements into the linkedlist and to count the number of nodes traverse the linkedlist starting from head to tail and keep a track on its total count.
Let’s see the program to understand it clealry.
Approach:
- Create a linked list by creating an object of that class.
- Call the user defined
count( )
method to print the number of nodes in the list. - Add some elements to the list.
- Print the linked list by calling user defined method
show()
in which we will traverse each element one by one and print it. - Call the
count( )
method again and see the number of nodes after the elements have been added.
Program:
import java.util.*; // Main class public class Main { // Class Node that defines the two linked list variables class Node { int data; Node nextNode; // constructor to create a node public Node(int data) { this.data = data; this.nextNode = null; } } // Setting the head and end of the node as NULL public Node head = null; public Node tail = null; // Count the number of nodes in the linked list public void count() { int c = 0; Node curr = head; //continue it till curr refers to null while(curr!=null) { c++; curr = curr.nextNode; } System.out.println("The number of nodes in the linked list currently are: "+c); } // method to add a node to the linked list public void add(int data) { Node newNode = new Node(data); // Checks if there was any previous node //if the list is empty then head and tail both will point to newNode if(head==null) { head = newNode; tail = newNode; } else { tail.nextNode = newNode; tail = newNode; } } // Method to display all the nodes of the linked list public void show() { Node curr = head; // If the head is pointing to no node then the linked list is empty if(head==null) System.out.println("Linked List is empty"); else { System.out.println("The nodes are:"); while(curr!=null) { System.out.print(curr.data+","); curr = curr.nextNode; } System.out.println(); } } //Driver method public static void main(String[] args) { // create an object of the main class Main ll = new Main(); // Counts the number of nodes in the linked list ll.count(); // add elements to the linked list ll.add(10); ll.add(20); ll.add(30); ll.add(40); ll.add(50); // display the nodes ll.show(); // Again counts the number of nodes ll.count(); } }
Output: The number of nodes in the linked list currently are: 0 The nodes are: 10,20,30,40,50, The number of nodes in the linked list currently are: 5
Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.