package Challenge_CB_LinkedList;
import java.util.Scanner;
public class FindIntersection {
Node head;
Node tail;
int size = 0;
static class Node {
int data;
Node next;
Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
void addLast(int data) {
Node node = new Node(data, null) ;
if(this.size == 0) {
this.head = node;
this.tail = node;
}else {
this.tail.next = node;
this.tail = node;
}
}
void push(int new_data, Node next) {
Node new_node = new Node(new_data,next);
new_node.next = head;
head = new_node;
}
static int NodeCount(Node cnode) {
Node node = cnode;
int count = 0;
while (node != null) {
count++;
node = node.next;
}
return count;
}
static int _auxfunc(Node head, Node head2) {
int count1 = NodeCount(head);
int count2 = NodeCount(head2);
int diff;
if (count1 > count2) {
diff = count1 - count2;
return interSection(head,head2,diff);
}
else
{
diff = count2 - count1;
return interSection(head2,head,diff);
}
}
static int interSection(Node node1, Node node2, int d) {
Node current1 = node1;
Node current2 = node2;
for(int i=0 ; i<d; i++) {
if(current1 == null) {
return -1;
}
current1 = current1.next;
}
while(current1 != null && current2 != null) {
if(current1.data == current2.data) {
return current1.data;
}
current1 = current1.next;
current2 = current2.next;
}
return -1;
}
public static void main(String[] args) {
FindIntersection LL = new FindIntersection();
FindIntersection LL2 = new FindIntersection();
Scanner scn = new Scanner(System.in);
int m = scn.nextInt();
while(m>0) {
LL.addLast(scn.nextInt());
m--;
}
int n = scn.nextInt();
while(n>0) {
LL2.addLast(scn.nextInt());
n--;
}
Node p1 = new Node(LL.head.data,LL.head);
Node p2 = new Node(LL2.head.data,LL2.head);
System.out.println(_auxfunc(p1,p2));
}
}