每天学习一点算法 2026/03/08
题目:相交链表
给你两个单链表的头节点
headA和headB,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回null。
-
我们可以先遍历一个链表将所有节点都存放在 Set 集合中,然后遍历另外一个链表遇到相同节点则表示这就是相交起始节点,如果没有相同节点则表示不存在相交节点。
typescript/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null { const set = new Set() while (headA) { set.add(headA) headA = headA.next } while (headB) { if (set.has(headB)) { return headB } headB = headB.next } return null }; -
双指针解法

我们看图中这种情况,我们可以看出
用一个指针遍历A链表,然后再遍历B链表,第二次到达相交节点的需要遍历的次数
和
用一个指针遍历B链表,然后再遍历A链表,第二次到达相交节点的需要遍历的次数
是相等的
所以我们可以用两个指针分别遍历 A → B 和 B → A,两个指针节点第一次相遇的节点就是相交的起始节点,如果两个指针都遍历完了还没相遇那就没有相交节点。
typescriptfunction getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null { let tempA = headA let tempB = headB while (tempA != tempB) { tempA = tempA == null ? headB : tempA.next tempB = tempB == null ? headA : tempB.next } return tempA };
题目来源:力扣(LeetCode)