854. Count Nodes in Linked ListPOTD

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

Example 1:

Input: head = 1 -> 2 -> 3 -> 4 -> null

Output: 4

Example 2:

Input: head = [1]

Output: 1

Now Your Turn!

Pick the correct output for the given input

Input: head = [1, 4]

Still unsure what the problem is asking ?

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

Constraints:

  • 1 <= Number of Nodes <= 105
  • Each node contains an integer value.
0
/*
Definition of singly linked list:
struct ListNode
{
int val;
ListNode *next;
ListNode()
{
val = 0;
next = NULL;
}
ListNode(int data1)
{
val = data1;
next = NULL;
}
ListNode(int data1, ListNode *next1)
{
val = data1;
next = next1;
}
};
*/
 
class Solution {
public:
int countNodes(ListNode* head) {
// Your code goes here
}
};
 
Test Case

Input:

Head