998. Find the length of the Linked List

You are given the head of a singly linked list. Your task is to return the number of nodes in the linked list.

Example 1:

Input: head = [1, 2, 3, 4, 5]

Output: 5

Example 2:

Input: head = [8, 6]

Output: 2

Now Your Turn!

Pick the correct output for the given input

Input: head = [1]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 0 <= number of nodes in the Linked List <= 105
  • 0 <= ListNode.val <= 104
0
class Solution {
public:
int getLength(ListNode* head) {
// Your code goes here
}
};
Test Case

Input:

Head