VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-length-of-a-linked-list-iterative-and-recursive/

⇱ Length of a Linked List (Iterative and Recursive) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Length of a Linked List (Iterative and Recursive)

Last Updated : 10 Sep, 2025

Given a Singly Linked List, the task is to find the Length of the Linked List.

Examples:

Input: LinkedList = 1->3->1->2->1
Output: 5
Explanation: The linked list has 5 nodes.

Input: LinkedList = 2->4->1->9->5->3->6
Output: 7
Explanation: The linked list has 7 nodes.

Input:LinkedList = 10->20->30->40->50->60
Output:6
Explanation: The linked list has 6 nodes.

Iterative Approach to Find the Length of a Linked List

The idea is similar to traversal of Linked List with an additional variable to count the number of nodes in the Linked List.

Steps to find the length of the Linked List:

  • Initialize count as 0. 
  • Initialize a node pointer, curr = head.
  • Do following while curr is not NULL
    • curr = curr -> next
    • Increment count by 1.
  • Return count.

Output
Count of nodes is 5

Time complexity: O(n), Where n is the size of the linked list
Auxiliary Space: O(1), As constant extra space is used.

Recursive Approach to Find the Length of a Linked List:

The idea is to use recursion by maintaining a function, say countNodes(node) which takes a node as an argument and calls itself with the next node until we reach the end of the Linked List. Each of the recursive call returns 1 + count of remaining nodes.


Output
Count of nodes is 5

Time Complexity: O(n), where n is the length of Linked List.
Auxiliary Space: O(n), Extra space is used in the recursion call stack.


Comment
Article Tags:
Article Tags: