AlgoViz

Find the length of the Linked List

Easy

Walk to the end, counting

Problem

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

In simple words

Walk from head to tail, counting one for each node until you fall off the end.

The idea

Start at the head and follow next pointers until null, incrementing a counter. There is no stored size, so this is inherently O(n) — which is why algorithms on lists try to avoid needing the length at all.

The trick

  • The loop condition is `node != null`, not `node.next != null`.
  • Many list problems avoid a length pass entirely by using two pointers.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

1
2
3
4
5
0
1
2
3
4

Step 1 of 2. Here's the example — head = [1, 2, 3, 4, 5] Values: 1, 2, 3, 4, 5.

1/2
Optimal
timeO(n)spaceO(1)
1count = 0; cur = head2while cur != null:3  count++; cur = cur.next4return count

Input

array
[1, 2, 3, 4, 5]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
list = 1 -> 2 -> 3 -> 4
Output:
4
Explanation:
Count the nodes → 4.

Example 2

Input:
list = 7
Output:
1
Explanation:
One node.

Example 3

Input:
list = (empty)
Output:
0
Explanation:
No nodes → 0.

Constraints

  • 0 <= number of nodes in the Linked List <= 10^5
  • 0 <= ListNode.val <= 10^4

Practice this problem:GeeksforGeeks(opens in a new tab)

Finished the walkthrough? Add it to your streak.