1. Understand the problem

1.1. Explain the main idea of the problem

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:

  1. The linked list always starts at node .
  2. A[i] represents the index of the next node after node i.
  3. If A[i] == -1, the current node is the last node.
  4. We only count nodes reachable by starting from node .
  5. Nodes that are not reachable from node do not belong to the linked list.

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: