Home » Program To Create A Singly Linked List Of N Nodes And Count The Number Of Nodes

Program To Create A Singly Linked List Of N Nodes And Count The Number Of Nodes

by Online Tutorials Library

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

Explanation

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

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

  1. Create a class Node which has two attributes: data and next. Next is a pointer to the next node in the list.
  2. Create another class which has two attributes: head and tail.
  3. addNode() will add a new node to the list:
    1. Create a new node.
    2. It first checks, whether the head is equal to null which means the list is empty.
    3. If the list is empty, both head and tail will point to the newly added node.
    4. 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.
  4. countNodes() will count the nodes present in the list:
    1. Define a node current which will initially point to the head of the list.
    2. Declare and initialize a variable count to 0.
    3. Traverse through the list till current point to null.
    4. Increment the value of count by 1 for each node encountered in the list.
  5. display() will display the nodes present in the list:
    1. Define a node current which will initially point to the head of the list.
    2. Traverse through the list till current points to null.
    3. Display each node by making current to point to node next to it in each iteration.

Solution

Python

Output:

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

C

Output:

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

JAVA

Output:

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

C#

Output:

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

PHP

Output:

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

Next Topic#

You may also like