NeetCode #310LC-160EasyLinked List
← Back to All Problems#310 · #160 · Intersection of Two Linked Lists(相交链表)
📌 Problem Statement & Constraints
Given the heads of two singly linked lists
headA and headB, return the node at which they intersect, or null if they do not. The lists may have different lengths. Constraints: the number of nodes is in [1, 10^5]. The follow-up asks for O(1) memory.💡 Core Algorithmic Approaches
- Two-pointer switching: advance both pointers; when one reaches the end, redirect it to the other list's head.
- After at most
lenA + lenBsteps, both pointers have travelled the same total distance, so they either meet at the intersection or both becomeNonesimultaneously. - This elegantly equalises the length difference without computing lengths explicitly.
- An alternative computes both lengths, advances the longer list's pointer by the difference, then walks in lockstep.
💻 Benchmark Python3 Implementation
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
a, b = headA, headB
while a is not b: # identity, not value equality
a = a.next if a else headB # switch to the other list at the end
b = b.next if b else headA
return a # None if no intersection
# Length-difference variant: explicit but equally O(1) space
class Solution2:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
def length(node):
n = 0
while node:
n += 1
node = node.next
return n
la, lb = length(headA), length(headB)
a, b = headA, headB
for _ in range(la - lb if la > lb else 0):
a = a.next
for _ in range(lb - la if lb > la else 0):
b = b.next
while a is not b:
a = a.next
b = b.next
return a⚡ Complexity Deep Dive
⏱️ Time Complexity
O(m + n): each pointer traverses at most both lists once.
💾 Space Complexity
O(1): two pointers.
⚠️ Interview Pitfalls & Follow-ups
- Comparing
a.val == b.val: nodes are identified by reference, and two distinct nodes may hold equal values. - Using a hash set of nodes: O(m) space, which the follow-up forbids.
- Not handling the no-intersection case: both pointers become
Noneat the same time, and the loop exits returningNone-- correct, provided thea is not bcomparison is used (not!=, which would be equivalent for objects but is better written as identity). - Switching pointers more than once: the loop handles it naturally, but the logic depends on switching exactly at the end of each traversal.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Linked List Problems
中文速览与面试要点
相交链表
给你两个单链表的头节点 headA 和 headB,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null。题目数据 保证 整个链式结构中不存在环。注意,函数返回结果后,链表必须 保持其原始结构 。约束:listA 中节点数目为 m;listB 中节点数目为 n;1 ≤ m, n ≤ 3 × 10^4;1 ≤ Node.val ≤ 10^5;0 ≤ skipA < m;0 ≤ skipB < n;如果 listA 和 listB 没有交点,intersectVal 为 0。
核心要点
- 双指针走对方的路(最优解) :指针 a 从 headA 出发,走到末尾后跳到 headB 继续;指针 b 从 headB 出发,走到末尾后跳到 headA 继续。若存在交点,两者必然在交点处相遇。
- 为什么必然相遇 :设两条链表的非公共部分长度分别为 a、b,公共部分长度为 c。两个指针走的总路程都是 a + b + c ,因此会同时到达交点。
- 若无交点 :两者都会在走完 m + n 步后同时变为 None,循环条件 a is not b 不成立(None is None),退出并返回 None。
- 替代方案 · 长度差法 :先求两链表长度,让长的先走差值步,然后同步前进。逻辑更直观但需要额外一趟求长度。
常见陷阱
- 用 a.val != b.val 判断相交 :值相同不代表是同一节点。必须用 is 比较对象身份。
- 跳到对方头部时写成 a = a.next (不判断 None) :会抛 AttributeError。必须用 a.next if a else headB 。
- 误以为无交点时会死循环 :两者会同时变为 None,循环退出。
- 用哈希集合记录 headA 的所有节点 :正确但需要 O(m) 空间。
参考实现
class Solution:
def getIntersectionNode(self, headA: 'ListNode', headB: 'ListNode') -> 'ListNode':
a, b = headA, headB
while a is not b:
# 走到末尾后跳到另一条链表的头部
a = a.next if a else headB
b = b.next if b else headA
return a # 有交点则返回交点,无交点则返回 None