題目鏈接:https://leetcode.com/problems/intersection-of-two-linked-lists/#/description
題目要求:找出兩個鏈表的交叉點,若兩鏈表沒有交叉點,返回null。
思路:(1)首先遍歷兩個鏈表,計算出兩個鏈表的長度 O(N)
(2)對於較長的那個鏈表,讓該鏈表的指針先走幾步——所走的步數爲兩鏈表的長度差
(3)再讓兩鏈表的指針每次走一步,若兩指針相遇了,那麼首次相遇的節點即爲兩鏈表的交叉節點;若不相遇,則兩個鏈表不存在交叉點。
Java代碼如下:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lengthA = 0;
int lengthB = 0;
ListNode current = headA;
// 計算出鏈表A和B的長度
while(current != null){
lengthA ++;
current = current.next;
}
current = headB;
while(current != null){
lengthB ++;
current = current.next;
}
int sub = Math.abs(lengthB - lengthA);
ListNode first = headA;
ListNode second = headB;
// 鏈表較長的那個對應的指針先走幾步——先走的步數爲兩個鏈表的長度差
if(lengthB > lengthA){
for(int i = 0; i<sub; i++){
second = second.next;
}
} else {
for(int i = 0; i<sub; i++){
first = first.next;
}
}
while(first!=null && second != null){
// 當兩個指針首次相遇時,即爲兩個鏈表的交叉點
if(first==second){
return first;
} else {
first = first.next;
second = second.next;
}
}
return null;
}
}