Skip to main content

Find the length of circular linked list

The problem involves finding the length of a circular linked list, which is the total number of nodes present in the linked list.

Problem Statement

Given a circular linked list, the task is to find the length of the linked list, i.e., the total number of nodes present in it.

Example

Consider the circular linked list: 1 -> 3 -> 5 -> 7 -> 9 -> 11 -> 1. The length of this circular linked list is 6.

Idea to Solve the Problem

Count number of node element

To find the length of a circular linked list, we can start from the head of the list and traverse through the linked list until we reach the head again. During this traversal, we count the number of nodes we encounter, which gives us the length of the linked list.

Pseudocode

Here's the pseudocode to find the length of a circular linked list:

function countNode():
    if head is NULL:
        return 0
    
    // Start with the second node
    temp = head.next
    // Initialize count to 1 (for the head node)
    count = 1
    while temp is not head:
        count = count + 1
        // Move to the next node
        temp = temp.next
    
    return count

Algorithm Explanation

  1. Check if the linked list is empty. If it's empty, return 0 since there are no nodes.
  2. Initialize temp to the second node (the node after the head) and count to 1 (for the head node).
  3. Use a loop to traverse the linked list while temp is not equal to the head node.
  4. Inside the loop, increment the count by 1 to count the current node.
  5. Move temp to the next node.
  6. After the loop, the count variable will contain the total number of nodes in the circular linked list, so return it.

Code Solution

Time Complexity

The time complexity of finding the length of a circular linked list is O(n), where n is the number of nodes in the linked list. This is because we traverse the entire linked list once to count the nodes.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment