Find the first shared node · Compiler

Find the first shared node

Two lists use nodes from one table. Find the first node on the walk from head A whose node ID also occurs on the walk from head B. Equal stored values can belong to different nodes.

Input
Read n A B (1 <= n <= 100), then n rows of value next. Row i gives the integer value in [-1000, 1000] and successor of node ID i, numbered from 1. Each head and successor is an ID in [1, n] or 0 for an empty link. Both walks end.
Output
Print the ID of the first shared node, or 0 if the lists share no node.

Compiler Explorer runs your code when you run or check it.

Loading your exercise draft…