題目表述
輸入兩個鏈表,找出它們的第一個公共結點。
首先要明白一點,兩條鏈表相交,則他們的形狀類似Y,而不是X。所以,從相交的點以後,兩條鏈表的所有結點都是一樣的。我們只要找出第一個相同的結點即可。
1.我們分別算出兩條鏈表的長度
2.算出兩條鏈表的長度差,併除去長的鏈表前面多餘的結點
3.同時遍歷,找出第一個相同的結點
public class Solution14 {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int l1=0,l2=0;
ListNode n1,n2;
n1=pHead1;
n2=pHead2;
//求兩條鏈表的長度
while(n1!=null){
l1++;
n1=n1.next;
}
while(n2!=null){
l2++;
n2=n2.next;
}
//讓兩條鏈表一樣長,在比較第一個一樣的
if(l1>l2){
int temp=l1-l2;
while(temp-->0){
pHead1=pHead1.next;
}
}else{
int temp=l2-l1;
while(temp-->0){
pHead2=pHead2.next;
}
}
while(pHead1!=null&&pHead2!=null){
if(pHead1.val==pHead2.val)
return pHead1;
pHead1=pHead1.next;
pHead2=pHead2.next;
}
return null;
}
public static void main(String[] args) {
int[] a = { 4, 5, 1, 6, 2, 7, 3, 8 };
Solution14 b = new Solution14();
// System.out.println(b.GetLeastNumbers_Solution(a,10));
}
}