Last Updated: 1 Jun, 2017

Count nodes of linked list

Easy
Asked in company
American Express

Problem statement

Given the head of a singly linked list of integers, find and return its length.


Example:

Sample Linked List

The length of the list is 4. Hence we return 4.


Note:
Exercise caution when dealing with edge cases, such as when the head is NULL. Failing to handle these edge cases appropriately may result in a runtime error in your code.


Input format :
The first and only line contains elements of the singly linked list separated by a single space, -1 indicates the end of the singly linked list and hence, would never be a list element.


Output format :
Return a single integer denoting the length of the linked list.

Approaches

01 Approach

The basic idea of this approach is to traverse the linked list.

Now consider the following steps:

  • It starts by initializing a variable ‘len’ to zero and a temporary pointer ‘temp’ to the ‘head’ of the list.
  • It then enters a loop that increments ‘len’ by one for each node in the list and moves the ‘temp’ pointer to the next node.
  • The loop continues until the end of the list is reached (when ‘temp’ becomes NULL).
  • Finally, the function returns the calculated length.