输入两个链表,找出它们的第一个公共结点。
java
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.lang.Math;
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null) {
return null;
}
ListNode p1 = pHead1;
ListNode p2 = pHead2;
int count1 = 0;
int count2 = 0;
while (p1 != null) {
p1 = p1.next;
count1++;
}
while (p2 != null) {
p2 = p2.next;
count2++;
}
if (count1 > count2) {
int k = count1 - count2;
while (k > 0) {
pHead1 = pHead1.next;
k--;
}
}
if (count2 > count1) {
int k = count2 - count1;
while (k > 0) {
pHead2 = pHead2.next;
k--;
}
}
int index = Math.min(count1, count2);
while (index > 0) {
if (pHead1.val == pHead2.val) {
return pHead1;
} else {
pHead1 = pHead1.next;
pHead2 = pHead2.next;
index--;
}
}
return null;
}
}