We are given an integer array A representing a singly linked list.
Each index represents a node, and the value at that index indicates the next node.
Rules:
A[i] represents the index of the next node after node i.A[i] == -1, the current node is the last node.Our task: Return the total number of nodes in the linked list, including the first and last nodes.
Example:
A = [5, -1, 6, 0, 1, 2, 1]
The linked list is:
0 → 5 → 2 → 6 → 1 → -1
Let's map each node to its next node:
| Current node | A[current node] | Next node |
|---|---|---|
| 0 | 5 | 5 |
| 5 | 2 | 2 |
| 2 | 6 | 6 |
| 6 | 1 | 1 |
| 1 | -1 | End |
Therefore:
Output = 5
Core problem-solving idea: