Find End of Linked List
You are given a linked list represented using an array of next pointers. The list is defined by an array next_arr of size N. next_arr[i] stores the index of the next element in the list. The list starts at index 0. If next_arr[i] is -1, it means element i is the last element in the list. Print the index of the last element. If the list is empty (N=0), print -1.
Input
The first line contains an integer N (0 <= N <= 1000). The second line contains N integers, where the i-th integer is next_arr[i] (-1 <= next_arr[i] < N, or next_arr[i] = -1).
Output
Print a single integer, the index of the last element of the linked list. Print -1 if the list is empty.
Constraints
0 <= N <= 1000. -1 <= next_arr[i] < N or next_arr[i] = -1.
Example 1
5 1 2 3 4 -1
4
The list is 0 -> 1 -> 2 -> 3 -> 4. The last element is at index 4.
Example 2
3 -1 0 1
0
The list starts at 0, and next_arr[0] is -1, so 0 is the last element.
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 -1 0 1