The Wayback Machine - https://web.archive.org/web/20240922034609/https://www.geeksforgeeks.org/count-nodes-circular-linked-list/
Open In App

Count nodes in Circular linked list

Last Updated : 31 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a circular linked list. The task is to find the length of the linked list, where length is defined as the number of nodes in the linked list.

Count-nodes-in-Circular-Linked-List

count nodes in the circular linked list.

Using linear traversal – O(n) time and O(1) space

The idea is to start from the head node and traversing the list until it loops back to the head. Since a circular linked list has no end, the traversal continues until the current node equals the head again. Increment the counter variable during each step of the traversal of nodes. Finally return the count, which represent the count of nodes in circular linked list.

C++
// C++ program to count number of nodes 
// in a circular linked list.

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;

    Node(int x) {
        data = x;
        next = nullptr;
    }
};

// Function to count nodes in a given Circular
// linked list 
int countNodes(Node* head) {
    if (head == nullptr) return 0;

    Node* curr = head;
    int result = 0;

    do {
        curr = curr->next;
        result++;
    } while (curr != head);

    return result;
}

int main() {
  
    // Create list: 1->2->3->4->5--->1
    Node* head = new Node(1);
    head->next = new Node(2);
    head->next->next = new Node(3);
    head->next->next->next = new Node(4);
    head->next->next->next->next = new Node(5);
    head->next->next->next->next->next = head;

    cout << countNodes(head);

    return 0;
}
C
// C program to count number of nodes 
// in a circular linked list.

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* next;
};

// Function to count nodes in a given Circular
// linked list 
int countNodes(struct Node* head) {
    if (head == NULL) return 0;

    struct Node* curr = head;
    int result = 0;

    do {
        curr = curr->next;
        result++;
    } while (curr != head);

    return result;
}

struct Node* createNode(int new_data) {
    struct Node* new_node = 
    (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = NULL;
    return new_node;
}

int main() {
    
    // Create list: 1->2->3->4->5--->1
    struct Node* head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);
    head->next->next->next = createNode(4);
    head->next->next->next->next = createNode(5);
    head->next->next->next->next->next = head;

    printf("%d", countNodes(head));

    return 0;
}
Java
// Java program to count number of nodes 
// in a circular linked list

class Node {
    int data;
    Node next;

    Node(int new_data) {
        data = new_data;
        next = null;
    }
}

// Function to count nodes in a given Circular
// linked list 
class GfG {

    static int countNodes(Node head) {
        if (head == null) return 0;

        Node curr = head;
        int result = 0;

        do {
            curr = curr.next;
            result++;
        } while (curr != head);

        return result;
    }

    public static void main(String[] args) {
        
        // Create list: 1->2->3->4->5--->1
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);
        head.next.next.next.next.next = head;

        System.out.println(countNodes(head));
    }
}
Python
# Python3 program to count number of 
# nodes in a circular linked list.

class Node: 
    def __init__(self, data): 
        self.data = data 
        self.next = None

# Function to count nodes 
# in a given Circular linked list 
def countNodes(head):

    curr = head
    result = 0

    # return 0 for empty lists
    if (head == None) :
        return 0
    
    while True :
        curr = curr.next
        result = result + 1
        if (curr == head):
            break
    
    return result

if __name__=='__main__': 

    # create list: 1->2->3->4->5--->1
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(3)
    head.next.next.next = Node(4)
    head.next.next.next.next = Node(5)
    head.next.next.next.next.next = head

    print(countNodes(head))
C#
// C++ program to count number of nodes 
// in a circular linked list

using System;

class Node {
    public int Data;
    public Node Next;

    public Node(int newData) {
        Data = newData;
        Next = null;
    }
}

// Function to count nodes in a given Circular
// linked list 
class GfG {
    static int CountNodes(Node head) {
        if (head == null) return 0;

        Node curr = head;
        int result = 0;

        do {
            curr = curr.Next;
            result++;
        } while (curr != head);

        return result;
    }

    static void Main() {
        
        // Create list: 1->2->3->4->5--->1
        Node head = new Node(1);
        head.Next = new Node(2);
        head.Next.Next = new Node(3);
        head.Next.Next.Next = new Node(4);
        head.Next.Next.Next.Next = new Node(5);
        head.Next.Next.Next.Next.Next = head;

        Console.WriteLine(CountNodes(head));
    }
}
JavaScript
// JavaScript program to count number 
// of nodes in a circular linked list
class Node {
    constructor(newData) {
        this.data = newData;
        this.next = null;
    }
}

// Function to count nodes in a 
// given Circular linked list
function countNodes(head) {
    var curr = head;
    var result = 0;

    // return 0 for empty lists
    if (head == null) return 0;

    do {
        curr = curr.next;
        result++;
    } while (curr != head);

    return result;
}

// Create list: 1->2->3->4->5--->1
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
head.next.next.next.next.next = head;

console.log(countNodes(head));

Output
5

Time Complexity: O(n), where n is the length of given linked list.
Auxiliary Space: O(1)



Similar Reads

Splitting starting N nodes into new Circular Linked List while preserving the old nodes
Given a circular linked list with N nodes and an integer K where 0 &lt; K &lt; N, the task is to split the first K nodes into a new list and at the same time preserving the rest of the nodes in the original circular linked list. Examples: Input: 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; 7 -&gt; 8, K = 3 Output: Original list: 2 3 4 5 6 7 8 The new li
13 min read
Circular Linked List Implementation of Circular Queue
Prerequisite – Circular Singly Linked List We have discussed basics and how to implement circular queue using array in set 1. Circular Queue | Set 1 (Introduction and Array Implementation) In this post another method of circular queue implementation is discussed, using Circular Singly Linked List. Operations on Circular Queue: Front:Get the front i
9 min read
Check if a linked list is Circular Linked List
Given the head of a singly linked list, the task is to find if given linked list is circular or not. A linked list is called circular if its last node points back to its first node. Note: The linked list does not contain any internal loops. Example: Input: LinkedList: 2-&gt;4-&gt;6-&gt;7-&gt;5 Output: trueExplanation: As shown in figure the first a
12 min read
Convert singly linked list into circular linked list
Given a singly linked list, the task is to convert it into a circular linked list. Examples: Input: head: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; NULLOutput: Explanation: Singly linked list is converted to circular by pointing last node to head. Input: head: 2 -&gt; 4 -&gt; 6 -&gt; 8 -&gt; 10 -&gt; 12 -&gt; NULLOutput: Explanation: Singly l
11 min read
Sum of the nodes of a Circular Linked List
Given a singly Circular linked list. The task is to find the sum of nodes of the given linked list. For the above circular list, sum = 2 + 5 + 7 + 8 + 10 = 32 Examples: Input: 11-&gt;2-&gt;56-&gt;12 Output: Sum of Circular linked list is = 81 Input: 2-&gt; 5 -&gt; 7 -&gt; 8 -&gt; 10 Output: Sum of Circular linked list is = 32 Approach: Initialize a
7 min read
Delete all the even nodes of a Circular Linked List
Given a circular singly linked list containing N nodes, the task is to delete all the even nodes from the list. Examples: Input : 57-&gt;11-&gt;2-&gt;56-&gt;12-&gt;61 Output : List after deletion : 57 -&gt; 11 -&gt; 61 Input : 9-&gt;11-&gt;32-&gt;6-&gt;13-&gt;20 Output : List after deletion : 9 -&gt; 11 -&gt; 13 The idea is to traverse the nodes of
10 min read
Delete all Prime Nodes from a Circular Singly Linked List
Given a circular singly linked list containing N nodes. The task is to delete all nodes from the list which are prime. Examples: Input : 9-&gt;11-&gt;32-&gt;6-&gt;13-&gt;20 Output : 9 32 6 20 Input : 6-&gt;11-&gt;16-&gt;21-&gt;17-&gt;10 Output : 6 16 21 10 Approach: The idea is to traverse the nodes of the circular singly linked list one by one and
13 min read
Delete all odd or even positioned nodes from Circular Linked List
Delete all odd or even position nodes from circular linked list Given a Singly Circular Linked List, starting from the first node delete all odd position nodes in it. Note: Linked list is considered to have 1-based indexing. That is, first element in the linked list is at position 1. Examples: Input : List = 99-&gt;11-&gt;22-&gt;33 Output : 11-&gt;
15+ min read
Sum and Product of the nodes of a Circular Singly Linked List which are divisible by K
Given a singly circular linked list. The task is to find the sum and product of nodes that are divisible by K of the given linked list. Examples: Input : List = 5-&gt;6-&gt;7-&gt;8-&gt;9-&gt;10-&gt;11-&gt;11 K = 11 Output : Sum = 22, Product = 121 Input : List = 15-&gt;7-&gt;3-&gt;9-&gt;11-&gt;5 K = 5 Output : Product = 75, Sum = 20 Approach: Initi
12 min read
Delete all odd nodes of a Circular Linked List
Prerequisite: Delete all the even nodes of a Circular Linked ListGiven a circular singly linked list containing N nodes, the task is to delete all the odd nodes from the list. Examples: Input: 572-&gt;112-&gt;21-&gt;5-&gt;1-&gt;6 Output: 572 -&gt; 112 -&gt; 6 Explanation: All the odd valued nodes have been deletedInput: 9-&gt;11-&gt;32-&gt;6-&gt;13
10 min read
Remove all Fibonacci Nodes from a Circular Singly Linked List
Given a circular singly linked list containing N nodes, the task is to remove all the nodes from the list which contains Fibonacci data values.Examples: Input: CLL = 9 -&gt; 11 -&gt; 34 -&gt; 6 -&gt; 13 -&gt; 20 Output: 9 -&gt; 11 -&gt; 6 -&gt; 20 Explanation: The list contains 2 fibonacci data values 32 and 13. Therefore, the nodes containing this
15+ min read
Sum and Product of nodes with value as even digit sum in Circular Linked List
Given a circular singly linked list containing N nodes, The task is to find the sum and product of all the nodes from the list whose data value has an even digit sum. Examples: Input: List = 15 -&gt; 16 -&gt; 8 -&gt; 6 -&gt; 13 Output: Sum = 42, Product = 9360 Explanation: The circular linked list contains: 15 -&gt; 1 + 5 = 6 16 -&gt; 1 + 6 = 7 8 -
11 min read
Remove all the Even Digit Sum Nodes from a Circular Singly Linked List
Given a circular singly linked list containing N nodes, the task is to remove all the nodes from the list which contains elements whose digit sum is even. Examples: Input: CLL = 9 -&gt; 11 -&gt; 34 -&gt; 6 -&gt; 13 -&gt; 21 Output: 9 -&gt; 34 -&gt; 21 Explanation: The circular singly linked list contains : 9 -&gt; 9 11 -&gt; 1 + 1 = 2 34 -&gt; 3 +
12 min read
Remove all even parity nodes from a Doubly and Circular Singly Linked List
Given a Doubly linked list and Circular singly linked list containing N nodes, the task is to remove all the nodes from each list which contains elements whose parity is even. Example: Input: CLL = 9 -&gt; 11 -&gt; 34 -&gt; 6 -&gt; 13 -&gt; 21 Output: 11 -&gt; 13 -&gt; 21 Explanation: The circular singly linked list contains : 11 -&gt; 1011, parity
15+ min read
Modify a Circular Doubly Linked List such that each node stores the sum of all nodes except itself
Given a circular doubly linked list consisting of N nodes, the task is to modify every node of the given Linked List such that each node contains the sum of all nodes except that node. Examples: Input: 4 ↔ 5 ↔ 6 ↔7 ↔ 8Output: 26 ↔ 25 ↔ 24 ↔ 23 ↔ 22Explanation:1st Node: Sum of all nodes except itself = (5 + 6 + 7 + 8) = 26.2nd Node: Sum of all nodes
15+ min read
Exchange first and last nodes in Circular Linked List
Given Circular linked list exchange the first and the last node. The task should be done with only one extra node, you can not declare more than one extra node, and also you are not allowed to declare any other temporary variable. Note: Extra node means the need of a node to traverse a list. Examples: Input : 5 4 3 2 1Output : 1 4 3 2 5 Input : 6 1
15+ min read
XOR linked list: Reverse last K nodes of a Linked List
Given a XOR Linked List and a positive integer K, the task is to reverse the last K nodes in the given XOR linked list. Examples: Input: LL: 7 &lt;–&gt; 6 &lt;–&gt; 8 &lt;–&gt; 11 &lt;–&gt; 3 &lt;–&gt; 1, K = 3Output: 7&lt;–&gt;6&lt;–&gt;8&lt;–&gt;1&lt;–&gt;3&lt;–&gt;11 Input: LL: 7 &lt;–&gt; 6 &lt;–&gt; 8 &lt;–&gt; 11 &lt;–&gt; 3 &lt;–&gt; 1 &lt;–
14 min read
Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
Given a linked list. The task is to segregate its even and odd position nodes in such a way that odd position nodes appear before even positioned nodes all the even positioned nodes must be in reverse order. Examples: Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; NULL Output : 1 -&gt; 3 -&gt; 5 -&gt; 6 -&gt; 4 -&gt; 2 -&gt; NULL Input : 1
11 min read
Javascript Program To Delete N Nodes After M Nodes Of A Linked List
Given a linked list and two integers M and N. Traverse the linked list such that you retain M nodes then delete next N nodes, continue the same till end of the linked list. Difficulty Level: Rookie Examples: Input:M = 2, N = 2Linked List: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8Output:Linked List: 1-&gt;2-&gt;5-&gt;6Input:M = 3, N = 2Linked List
3 min read
Delete N nodes after M nodes of a linked list
Given a linked list and two integers m and n, the task is to traverse the linked list such that you skip m nodes, then delete the next n nodes, and continue the same till end of the linked list. Note: m cannot be 0. Example: Input: Linked List: 9-&gt;1-&gt;3-&gt;5-&gt;9-&gt;4-&gt;10-&gt;1, n = 1, m = 2 Output: 9-&gt;1-&gt;5-&gt;9-&gt;10-&gt;1 Expla
10 min read
Count duplicates in a given circular linked list
Given a circular linked list, the task is to check whether the given list has duplicates or not. Example: Input: list = {5, 7, 5, 1, 4, 4}Output: 2Explanation: The given list has 2 indices having integers which has already occurred in the list during traversal. Input: list = {1, 1, 1, 1, 1}Output: 4 Approach: The given problem has a very similar so
6 min read
Insertion in an empty List in the circular linked list
A circular linked list is a type of data structure where each node points to the next one, and the last node connects back to the first, forming a circle. This setup allows you to loop through the list without stopping. Knowing how to insert a node into an empty circular linked list is important in creating circular linked list. Insertion in an emp
5 min read
Find a set of at most N/2 nodes from a Graph such that all remaining nodes are directly connected to one of the chosen nodes
Given an integer N, representing the number of nodes present in an undirected graph, with each node valued from 1 to N, and a 2D array Edges[][], representing the pair of vertices connected by an edge, the task is to find a set of at most N/2 nodes such that nodes that are not present in the set, are connected adjacent to any one of the nodes prese
12 min read
Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end. The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists). You are allowed to us
14 min read
What is Circular Queue | Circular Queue meaning
A circular queue is an extended version of regular queue in which the last element of the queue is connected to the first element of the queue forming a cycle. Properties of Circular Queue: Along with the properties of a regular queue the circular queue has som other unique properties as mentioned below: Front and rear pointers: Two pointers, one a
4 min read
Count occurrences of one linked list in another Linked List
Given two linked lists head1 and head2, the task is to find occurrences of head2 in head1. Examples: Input: Head1 = 1-&gt;2-&gt;3-&gt;2-&gt;4-&gt;5-&gt;2-&gt;4, Head2 = 2-&gt;4Output: Occurrences of head2 in head1: 2 Input: Head1 = 3-&gt;4-&gt;1-&gt;5-&gt;2, Head2 = 3-&gt;4Output: Occurrences of Head2 in Head1: 1 Approach 1: To solve the problem us
15 min read
Count pair of nodes with greater Bitwise AND than Bitwise XOR in given Linked List
Given a singly linked list, the task is to Count the pairs of nodes with greater Bitwise AND than Bitwise XOR. Examples: Input: list: 1-&gt;4-&gt;2-&gt;6-&gt;3Output: 2Explanation: 1st List Node Pair: (4, 6 ), Bitwise AND = 4, Bitwise XOR = 22nd List Node Pair: (2, 3), Bitwise AND = 2, Bitwise XOR = 1 Input: list: 17-&gt;34-&gt;62-&gt;46-&gt;30-
13 min read
Count of Prime Nodes of a Singly Linked List
Given a singly linked list containing N nodes, the task is to find the total count of prime numbers. Examples: Input: List = 15 -&gt; 5 -&gt; 6 -&gt; 10 -&gt; 17Output: 25 and 17 are the prime nodesInput: List = 29 -&gt; 3 -&gt; 4 -&gt; 2 -&gt; 9Output: 32, 3 and 29 are the prime nodesApproach: The idea is to traverse the linked list to the end and
15 min read
Circular Linked List meaning in DSA
A circular linked list is a special type of linked list in which the last node is connected to the first node, creating a continuous loop. In a circular linked list, each node has a reference to the next node in the sequence, just like in a regular linked list, but the last node's reference points back to the first node. Characteristics of Circular
3 min read
Applications, Advantages and Disadvantages of Circular Doubly Linked List
The circular doubly linked list is a combination of the doubly linked list and the circular linked list. It means that this linked list is bidirectional and contains two pointers and the last pointer points to the first pointer. Applications of Circular Doubly Linked List: Music and video playlists: Circular doubly linked lists are commonly used to
4 min read