Java program to create a singly linked list of n nodes and count the number of nodes

In this program, we need to create a singly linked list and count the nodes present in the list.

Java program to create a singly linked list of n nodes and count the number of nodes

To accomplish this task, traverse through the list using node current which initially points to head. Increment current in such a way that current will point to its next node in each iteration and increment variable count by 1. In the end, the count will hold the value which denotes the number of nodes present in the list.

Algorithm

  • Create a class Node which has two attributes: data and next. Next is a pointer to the next node in the list.
  • Create another class which has two attributes: head and tail.
  • addNode() will add a new node to the list:
    • Create a new node.
    • It first checks, whether the head is equal to null which means the list is empty.
    • If the list is empty, both head and tail will point to the newly added node.
    • If the list is not empty, the new node will be added to end of the list such that tail's next will point to a newly added node. This new node will become the new tail of the list.

a. countNodes() will count the nodes present in the list:

  • Define a node current which will initially point to the head of the list.
  • Declare and initialize a variable count to 0.
  • Traverse through the list till current point to null.
  • Increment the value of count by 1 for each node encountered in the list.

a. display() will display the nodes present in the list:

  • Define a node current which will initially point to the head of the list.
  • Traverse through the list till current points to null.
  • Display each node by making current to point to node next to it in each iteration.

Program:

Output:

Nodes of the singly linked list:
1 2 3 4 
Count of nodes present in the list: 4
Next TopicJava Programs




Latest Courses