oneby7

Linked Lists Singly linked list basics

262. Length of a Linked List

Easy

You are given head, the first node of a singly linked list. Return the number of nodes in the list.

Each node holds a value and a pointer to the next node, and the last node's pointer is null. An empty list has no nodes, and its head is null. Its length is 0.

The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. Your function gets only the head node, not this array.

Example 1

8-32105

Input: head = [8, -3, 21, 0, 5]

Output: 5

Explanation: The head holds 8. Its pointer leads to -3, then to 21, 0 and 5. The node holding 5 points to null, so the list has five nodes.

Example 2

0-90

Input: head = [0, -9, 0]

Output: 3

Explanation: Two nodes hold 0. Each node counts once, whatever its value, so the length is 3.

Example 3

Input: head = []

Output: 0

Explanation: The list is empty, so head is null and there are no nodes to count.

Check your understanding

Work out the answer for this input before you write any code.

head = [5, 2, 8, 1]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.