- 要明確一點的是,兩個鏈表如果相交的話,那麼從相交的第一個結點往後,這兩個鏈表會是這樣子滴:
爲啥呢?如果鏈表相交的話,說明各自鏈表的當前結點的信息是完完全全是一樣的,比如這個結點的結構是這樣子滴{ Node next, int val},next指針一樣,val值一樣,所以,第一個相交結點的結點就匯成了一條了,像個倒y。
- 可以先求下各自鏈表的長度,就上面的圖舉個例子,長的那個l1, 短的那個l2, l1.size - l2.size剛好就是長的那條比短的那條讀出來的長度,長的先走完這個長度差,就可以跟短的那個鏈表從同一起點同時開始遍歷比較每個結點啦。只要有相同的,就說明找到第一個相交的結點啦!
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1 == null || pHead2 == null)
return null;
int size_1 = getSize(pHead1);
int size_2 = getSize(pHead2);
int dif = 0;
if(size_1 > size_2){
dif = size_1 - size_2;
pHead1 = walk(pHead1,dif);
}else{
dif = size_2 - size_1;
pHead2 = walk(pHead2, dif);
}
while(pHead1 != null){
if(pHead1 == pHead2)
return pHead1;
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return null;
}
private ListNode walk(ListNode head, int dif){
while(dif > 0){
head = head.next;
dif --;
}
return head;
}
private int getSize(ListNode head){
if(head == null)
return 0;
ListNode cur = head;
int cnt = 0;
while(cur != null){
cur = cur.next;
cnt++;
}
return cnt;
}
}