Home » Program to Create a Circular Linked List of N Nodes and Count the Number of Nodes

Program to Create a Circular Linked List of N Nodes and Count the Number of Nodes

by Online Tutorials Library

Q. Program to create a circular linked list of n nodes and count the number of nodes.

Explanation

In this program, we have to find out the number of nodes present in the circular linked list. We first create the circular linked list, then traverse through the list and increment variable ‘count’ by 1.

Algorithm

  1. Define a Node class which represents a node in the list. It has two properties data and next which will point to the next node.
  2. Define another class for creating the circular linked list and it has two nodes: head and tail. It has two methods: add() and display() .
  3. add() will add the node to the list:
    1. It first checks whether size is null or head is null; then it will insert the node as the head.
    2. Both head and tail will point to a newly added node.
    3. If the head is not null, the new node will be the new tail, and new tail will point to the head as it is a circular linked list.
  4. countNodes() will count the number of nodes present in the list.
    1. Define new node current which will point to the head node.
    2. Traverse through the list to count the nodes by making the current node to point to next node in the list till current points to head again.

Solution

Python

Output:

Count of nodes present in circular linked list: 6  

C

Output:

Count of nodes present in circular linked list: 6  

JAVA

Output:

Count of nodes present in circular linked list: 6  

C#

Output:

Count of nodes present in circular linked list: 6  

PHP

Output:

Count of nodes present in circular linked list: 6  

Next Topic#

You may also like