← 返回题库
初级

相交链表

未完成
初级参考 完整示例代码供参考,建议自己理解后重新输入
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def solve():
    def getIntersectionNode(headA, headB):
        if not headA or not headB:
            return None
        pA, pB = headA, headB
        while pA != pB:
            pA = pA.next if pA else headB
            pB = pB.next if pB else headA
        return pA
    a1 = ListNode(4)
    a2 = ListNode(1)
    b1 = ListNode(5)
    b2 = ListNode(6)
    b3 = ListNode(1)
    c1 = ListNode(8)
    c2 = ListNode(4)
    c3 = ListNode(5)
    a1.next = a2
    a2.next = c1
    b1.next = b2
    b2.next = b3
    b3.next = c1
    c1.next = c2
    c2.next = c3
    result = getIntersectionNode(a1, b1)
    print(result.val if result else None)

示例

输入
solve()
期望输出
8
Python 代码 🔒 登录后使用
🔒

登录后即可练习

注册免费账号,在浏览器中直接运行 Python 代码