方法一:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
List<Integer> list = new ArrayList<Integer>();
while (pHead1 != null){
list.add(pHead1.val);
pHead1 = pHead1.next;
}
while (pHead2 != null){
if (list.contains(pHead2.val)){
return pHead2;
}
pHead2 = pHead2.next;
}
return null;
}
}
方法二:
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode p1 = pHead1;
ListNode p2 = pHead2;
while (p1 != p2){
p1 = p1 == null ? pHead2 : p1.next;
p2 = p2 == null ? pHead1 : p2.next;
}
return p1;
}
}