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 分钟前
LeetCode216
算法·深度优先
leeyayai_xixihah7 分钟前
2.21力扣-回溯组合
算法·leetcode·职场和发展
01_10 分钟前
力扣hot100——相交,回文链表
算法·leetcode·链表·双指针
萌の鱼10 分钟前
leetcode 2826. 将三个组排序
数据结构·c++·算法·leetcode
Buling_011 分钟前
算法-哈希表篇08-四数之和
数据结构·算法·散列表
AllowM13 分钟前
【LeetCode Hot100】除自身以外数组的乘积|左右乘积列表,Java实现!图解+代码,小白也能秒懂!
java·算法·leetcode
RAN_PAND38 分钟前
STL介绍1:vector、pair、string、queue、map
开发语言·c++·算法
fai厅的秃头姐!3 小时前
C语言03
c语言·数据结构·算法
醉城夜风~3 小时前
[数据结构]单链表详解
数据结构·链表
lisanndesu3 小时前
动态规划
算法·动态规划