To solve this problem, we need to find the starting node where two linked lists intersect. The key insight here is to use a two-pointer technique that allows us to traverse both lists without calculating their lengths explicitly.
Approach
The core idea is to use two pointers that traverse both lists. Here's the detailed approach:
- Initialize Two Pointers: Start with two pointers,
p1andp2, pointing to the heads of the two lists (headAandheadBrespectively). - Traverse Both Lists: Move each pointer one step at a time. If a pointer reaches the end of its list, redirect it to the head of the other list.
- Check for Intersection: The pointers will meet at the intersection node if it exists. If there's no intersection, both pointers will reach the end of the lists (null) at the same time.
Solution Code
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def getIntersectionNode(headA: ListNode, headB: ListNode) -> ListNode:
p1, p2 = headA, headB
while p1 != p2:
p1 = p1.next if p1 else headB
p2 = p2.next if p2 else headA
return p1
Explanation
Let’s break down the solution:
- Traversal: Each pointer (
p1andp2) traverses both lists. For example,p1goes throughheadAthenheadB, andp2goes throughheadBthenheadA. - Intersection Check: The total distance each pointer travels is the sum of the lengths of both lists. If there’s an intersection, the pointers will meet at the start of the common segment. If there’s no intersection, both pointers will reach
nullat the same time (since the total distance is the same for both).
This approach runs in O(L1 + L2) time (where L1 and L2 are the lengths of the two lists) and uses O(1) additional space, making it efficient and optimal.
Example:
- List1: 1 → 2 → 3 → 4
- List2: 5 → 3 →4
p1path: 1→2→3→4→5→3p2path:5→3→4→1→2→3- They meet at node 3 (the intersection point).
Another example with no intersection:
- List1:1→2→3
- List2:4→5
p1path: 1→2→3→4→5→nullp2path:4→5→1→2→3→null- Both reach
nullat the same time, so returnnull.
This solution handles all edge cases (empty lists, same lists, intersection at the first node, etc.) correctly. It’s an elegant and efficient way to find the intersection of two linked lists.


作者声明:本文包含人工智能生成内容。