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
相关推荐
Darkwanderor1 小时前
什么数据量适合用什么算法
c++·算法
zc.ovo1 小时前
河北师范大学2026校赛题解(A,E,I)
c++·算法
py有趣2 小时前
力扣热门100题之环形链表
算法·leetcode·链表
py有趣2 小时前
力扣热门100题之回文链表
算法·leetcode·链表
Kk.08022 小时前
数据结构|链表 刷题
数据结构·链表
月落归舟3 小时前
帮你从算法的角度来认识二叉树---(二)
算法·二叉树
SilentSlot4 小时前
【数据结构】Hash
数据结构·算法·哈希算法
样例过了就是过了5 小时前
LeetCode热题100 柱状图中最大的矩形
数据结构·c++·算法·leetcode
wsoz6 小时前
Leetcode哈希-day1
算法·leetcode·哈希算法