編寫一個程序,找到兩個單鏈表相交的起始節點。
如下面的兩個鏈表:
在節點 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 個節點。
?
示例?3:
輸入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
輸出:null
輸入解釋:從各自的表頭開始算起,鏈表 A 為 [2,6,4],鏈表 B 為 [1,5]。由于這兩個鏈表不相交,所以 intersectVal 必須為 0,而 skipA 和 skipB 可以是任意值。
解釋:這兩個鏈表不相交,因此返回 null。
?
注意:
如果兩個鏈表沒有交點,返回 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(headB==null || headA==null){return null;}ListNode tempA=headA;ListNode tempB=headB;int a=0;int b=0;while(tempA.next!=null){tempA=tempA.next;a++;}while(tempB.next!=null){tempB=tempB.next;b++;}if(tempB!=tempA){return null;}tempA=headA;tempB=headB;if(a>b){for(int i=0;i<a-b;i++){tempA=tempA.next;}}else{for(int i=0;i<b-a;i++){tempB=tempB.next;}}while(tempB!=tempA){tempA=tempA.next;tempB=tempB.next;}return tempA;}
}
?