考前不刷题,靠后徒伤悲 力扣力扣 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
};