Find Next Node
You are given a linked list represented using an array. An array next_nodes of size N is given, where next_nodes[i] is the index of the next node after node i. The first node of the list is at index 0. Your task is to find the index of the node that comes immediately after the node at index K. If K is out of bounds or the node K has no next node (indicated by -1), print -1.
Input
The first line contains two integers N and K, separated by a space. The second line contains N integers representing the next_nodes array.
Output
Print a single integer: the index of the node after K, or -1 if it doesn't exist.
Constraints
1 <= N <= 1000 0 <= K < N -1 <= next_nodes[i] < N for all i
Example 1
5 2 1 2 3 -1 0
3
N=5, K=2. next_nodes[2] is 3. The node after index 2 is index 3.
Example 2
4 3 1 2 0 -1
-1
N=4, K=3. next_nodes[3] is -1. The node at index 3 has no successor.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
5 2 1 2 3 -1 0
4 3 1 2 0 -1