/**
* 兩個鏈表的第一個公共節點
* <p>
* 先計算兩個鏈表的長度,讓長的鏈表先走兩個鏈表的差值,然後一起走,比較相等
*
* @param l1
* @param l2
* @return
*/
public ListNode findFirstCommonNode(ListNode l1, ListNode l2) {
if (null == l1 || null == l2) return null;
int size1 = 0;
ListNode head = l1;
while (head != null) {
size1++;
head = head.next;
}
head = l2;
int size2 = 0;
while (head != null) {
size2++;
head = head.next;
}
if (size1 > size2) {
int diff = size1 - size2;
while (diff > 0) {
diff--;
l1 = l1.next;
}
} else {
int diff = size2 - size1;
while (diff > 0) {
diff--;
l2 = l2.next;
}
}
while (l1 != null && l2 != null) {
if (l1 == l2) return l1;
l1 = l1.next;
l2 = l2.next;
}
return null;
}
劍指Offer學習-面試題52:兩個鏈表的第一個公共節點
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.