Array List Traversal
You are given an array next_indices of size N. The element next_indices[i] stores the index of the next element to visit after i. You start at index 0. Traverse the array following the next_indices links until you reach an index that has already been visited. Print the indices visited in the order they were first visited, up to (but not including) the first repeated index. If index 0 is immediately repeated (i.e., next_indices[0] == 0), print only '0'.
Input
The first line contains an integer N. The second line contains N space-separated integers representing the next_indices array.
Output
Print the sequence of visited indices, separated by spaces.
Constraints
1 <= N <= 1000. 0 <= next_indices[i] < N for all i.
Example 1
5 1 2 3 4 1
0 1 2 3 4
Starts at 0, goes to 1, then 2, then 3, then 4. Next is 1, which was already visited. Output: 0 1 2 3 4.
Example 2
3 0 1 2
0
Starts at 0. next_indices[0] is 0, which is already visited. Output: 0.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
5 1 2 3 4 1
3 0 1 2