題目描述:編寫一個程序,找到兩個單鏈表相交的起始節點。如下面的兩個鏈表:
在節點 c1 開始相交。
示例 1:
輸入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
輸出:Reference of the node with value = 8
輸入解釋:相交節點的值爲 8 (注意,如果兩個列表相交則不能爲 0)。從各自的表頭開始算起,鏈表 A 爲 [4,1,8,4,5],鏈表 B 爲 [5,0,1,8,4,5]。在 A 中,相交節點前有 2 個節點;在 B 中,相交節點前有 3 個節點。
示例 2:
輸入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
輸出:Reference of the node with value = 2
輸入解釋:相交節點的值爲 2 (注意,如果兩個列表相交則不能爲 0)。從各自的表頭開始算起,鏈表 A 爲 [0,9,1,2,4],鏈表 B 爲 [3,2,4]。在 A 中,相交節點前有 3 個節點;在 B 中,相交節點前有 1 個節點。
注意:
如果兩個鏈表沒有交點,返回 null.
在返回結果後,兩個鏈表仍須保持原有的結構。
可假定整個鏈表結構中沒有循環。
程序儘量滿足 O(n) 時間複雜度,且僅用 O(1) 內存
解釋:定義兩個指針,第一輪讓兩個到達末尾的節點指向另一個鏈表的頭部,最後若相遇則爲交點(第一輪移動中消除了長度差)兩個指針移動了相同的距離,若存在交點則返回,否則無交點,即各走了兩條指針的長度
代碼:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null || headB==null) return null;
ListNode post=headB;//
while(post.next!=null){
post=post.next;
}
post.next=headB;//鏈表B構建成環
ListNode first=headA;//快指針
ListNode last=headA;//慢指針
while(first!=null && first.next!=null){
last=last.next;//指針下移
first=first.next.next;//指針下移
if(last==first){//若兩指針相遇,則A有環
last=headA;//將其中一個指針指向A的頭節點
while(last!=first){//此時兩指針再相遇的地方就是兩鏈表相交的地方
last=last.next;
first=first.next;
}
post.next=null;
return first;//兩鏈表相交節點
}
}
post.next=null;
return null;
}
}