You are given head, a reference to a node in a circular singly linked list. Return the number of distinct nodes in the list.
Every node in a non-empty list is part of the cycle. The last node's next pointer leads back to head, and no part of the list sits outside the cycle. An empty list is given as head = None, and its length is 0.
Two nodes can hold the same value, so a repeated value does not mean you have come back to head. Compare node identity, not node values.
For example, the list [5, 5, 7] looks like this:
+---+ +---+ +---+
| 5 | -> | 5 | -> | 7 |
+---+ +---+ +---+
^ |
+-----------------+
Function Signature
def circular_list_length(head: Optional[ListNode]) -> int:
Rules
-
Each
ListNode
has an integer field
val
and a field
next
that refers to the following node.
-
In the examples, a list is written as the values of its nodes in order, starting at
head
. The last node's
next
is the first node, so
[42]
is a single node whose
next
is itself, and
[]
means
head = None
.
Constraints
-
The number of nodes in the list is between 0 and
10^4
.
-
-10^9 <= Node.val <= 10^9
-
In a non-empty list, the last node's
next
points back to
head
.
Examples
Input: head = [5, 5, 7]
Output: 3
The list has three distinct nodes. The second node holds the same value as head, but it is a different node, so counting continues until the traversal comes back to the head node itself.
Input: head = [42]
Output: 1
The single node points to itself, so the length is 1.
Input: head = []
Output: 0
An empty list has no nodes.