python-leetcode-相交链表

160. 相交链表 - 力扣(LeetCode)

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        if not headA or not headB:
            return None

        pA, pB = headA, headB

        while pA != pB:
            # 当 pA 走完 A 链表后,跳到 B 链表
            pA = pA.next if pA else headB
            # 当 pB 走完 B 链表后,跳到 A 链表
            pB = pB.next if pB else headA

        return pA  # 若相交返回交点,否则返回 None
相关推荐
张辰宇-7 分钟前
AcWing 5 多重背包问题 II
算法
小则又沐风a22 分钟前
类和对象(C++)---上
java·c++·算法
季明洵27 分钟前
动态规划及背包问题
java·数据结构·算法·动态规划·背包问题
busideyang34 分钟前
函数指针类型定义笔记
c语言·笔记·stm32·单片机·算法·嵌入式
Wect35 分钟前
LeetCode 215. 数组中的第K个最大元素:大根堆解法详解
前端·算法·typescript
深邃-1 小时前
数据结构-双向链表
c语言·开发语言·数据结构·c++·算法·链表·html5
2401_878530211 小时前
分布式任务调度系统
开发语言·c++·算法
_深海凉_1 小时前
LeetCode热题100-两数之和
算法·leetcode·职场和发展
nunca_te_rindas1 小时前
算法刷体小结汇总(C/C++)20260328
c语言·c++·算法
Sunshine for you1 小时前
高性能压缩库实现
开发语言·c++·算法