Data Structures

Length of a Linked List

Given the head of a Linked List, return the length of the list.

Example:

=> returns 5\notag \large \texttt{=> returns 5}

Explanation: There are 5 nodes in the Linked List.

First Few Test Cases:

We can walk along the Linked List and count the number of nodes we've seen so far. We'll return the count at the end.

Time Complexity O(n)O(n). We have to step through every node in the Linked List. If there are nn nodes in the Linked List, we have to do nn total steps. This means the total number of operations we have to do is O(n)O(n).

Space Complexity O(1)O(1). Our algorithm uses 2 variables, called count and node. This means we have to store O(2)O(2) variables, which is the same as O(1)O(1) variables. Remember, O(1)O(1) means the memory doesn't depend on the size of the array. As nn gets big, the amount of memory grows like the number 1 does - not at all.

Mark as Completed:
Submits:
listLength
Imports:
ListNode
Test your code to get an output here!
listLength(
)
Test your code to get an output here!