内容中心

2026年评价高的制氮机价格口碑好的厂家推荐-苏州希特高纯气体设备有限公司

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:

  1. Initialize Two Pointers: Start with two pointers, p1 and p2, pointing to the heads of the two lists (headA and headB respectively).
  2. 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.
  3. 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 (p1 and p2) traverses both lists. For example, p1 goes through headA then headB, and p2 goes through headB then headA.
  • 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 null at 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
  • p1 path: 1→2→3→4→5→3
  • p2 path: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
  • p1 path: 1→2→3→4→5→null
  • p2 path:4→5→1→2→3→null
  • Both reach null at the same time, so return null.

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.

苏州希特高纯气体设备有限公司

苏州希特高纯气体设备有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?