![]() |
VOOZH | about |
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.
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:
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.
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.
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.