考前不刷題,靠後徒傷悲 力扣力扣 https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
# 160 相交鏈表
編寫一個程序,找到兩個單鏈表相交的起始節點。
輸入: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 個節點。
方法一:暴力法
對鏈表A中的每一個結點 a_iai,遍歷整個鏈表 B
並檢查鏈表 B
中是否存在結點和 a_iai 相同。
方法二:哈希表
遍歷鏈表 A 並將每個結點的地址/引用存儲在哈希表中。然後檢查鏈表 B 中的每一個結點 b_i是否在哈希表中。若在,則 b_i爲相交結點。
方法三:快慢指針
/**
* 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) {
ListNode pA = headA;
ListNode pB = headB;
if(headA == null && headB == null){
return null;
}
while(pA!=pB){
if(pA == null){
pA = headB;
}else{
pA = pA.next;
}
if(pB == null){
pB = headA;
}else{
pB = pB.next;
}
}
return pA;
}
}
var getIntersectionNode = function(headA, headB) {
// 清除高度差
let pA = headA, pB = headB
while(pA || pB) {
if(pA === pB) return pA
pA = pA === null ? headB : pA.next
pB = pB === null ? headA : pB.next
}
return null
};