298. Find the Length of a Linked List

EasyLinked ListLinked ListTraversal

Given the head of a singly linked list, return the total number of nodes in the list.

Traverse the list from head to tail and count each node.

Input: Head node of a singly linked list.

Output: An integer representing the number of nodes.

Examples

Example 1
Input: [1,2,3,4,5]
Output: 5
Explanation: The list has 5 nodes: 1→2→3→4→5. Traversing from head to NULL gives count=5.
Example 2
Input: [10,20,30]
Output: 3
Explanation: Three nodes: 10→20→30. Count increments to 3.
Example 3
Input: [7]
Output: 1
Explanation: Single node list. Count = 1.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →