题解——相交链表(力扣160 easy)

160. 相交链表

算法思路

  1. 核心思想

    • 使用两个指针 pApB,分别从 headAheadB 开始遍历。
    • pA 遍历到链表 A 的末尾时,跳转到链表 B 的头节点;当 pB 遍历到链表 B 的末尾时,跳转到链表 A 的头节点。
    • 如果两个链表相交,pApB 最终会在相交节点相遇;如果不相交,pApB 会同时到达 None
  2. 具体步骤

    • 初始化 pA = headApB = headB
    • pA != pB 时:
      • 如果 pA 为空,跳转到 headB;否则继续遍历 pA.next
      • 如果 pB 为空,跳转到 headA;否则继续遍历 pB.next
    • 返回 pA(即相交节点)。
  3. 关键点

    • 通过跳转指针的方式,确保两个指针遍历的总长度相同。
    • 时间复杂度为 O(m + n),空间复杂度为 O(1)
python 复制代码
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA, headB):
        if not headA or not headB:
            return None
        
        pA, pB = headA, headB
        while pA != pB:
            pA = headB if not pA else pA.next
            pB = headA if not pB else pB.next
        
        return pA

题解里看到的图解,很清晰

相关推荐
DoraBigHead27 分钟前
小哆啦解题记——两数失踪事件
前端·算法·面试
不太可爱的大白27 分钟前
Mysql分片:一致性哈希算法
数据库·mysql·算法·哈希算法
Tiandaren4 小时前
Selenium 4 教程:自动化 WebDriver 管理与 Cookie 提取 || 用于解决chromedriver版本不匹配问题
selenium·测试工具·算法·自动化
岁忧5 小时前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_7895 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
秋说7 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy8 小时前
力扣61.旋转链表
算法·leetcode·链表
谭林杰9 小时前
B树和B+树
数据结构·b树
卡卡卡卡罗特10 小时前
每日mysql
数据结构·算法
chao_78910 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找