题目:输入两个链表,找出它们的第一个公共结点。
代码:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.*;
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
HashSet<Integer> sets1 = new HashSet<Integer>();
HashSet<Integer> sets2 = new HashSet<Integer>();
if(pHead1==null || pHead2==null)
return null;
else{
ListNode p1,p2;
p1=pHead1;p2=pHead2;
while(p1!=null ){
if(!sets1.contains(p1.val)){
sets1.add(p1.val);
}
p1=p1.next;
}
while(p2!=null){
if(sets1.contains(p2.val)){
return p2;
}else{
p2=p2.next;
}
}
}
return null;
}
}