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
相关推荐
今禾21 分钟前
一行代码引发的血案:new Array(5) 到底发生了什么?
前端·javascript·算法
橙几31 分钟前
击败了90%的解法?Two Sum 从 O(n²) 到 O(n) 的优化之路
算法
叶子爱分享1 小时前
经典排序算法之归并排序(Merge Sort)
算法·排序算法
珹洺1 小时前
C++算法竞赛篇:DevC++ 如何进行debug调试
java·c++·算法
Norvyn_71 小时前
LeetCode|Day18|20. 有效的括号|Python刷题笔记
笔记·python·leetcode
呆呆的小鳄鱼1 小时前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香2 小时前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely2 小时前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_07122 小时前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_2 小时前
cf1925B&C
数据结构·算法