LeetCode 160 Intersection of Two Linked Lists (Python)

Posted by 小明MaxMing on March 4, 2021

题目

Write a program to find the node at which the intersection of two singly linked lists begins.

解题思路

两个指针同时遍历两个链表,当到达一个尾骨之后,换到另一的头部继续遍历,两个指针会在链表的相交节点相遇

代码

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if not headA or not headB:
            return None
        pa, pb = headA, headB
        while pa is not pb:
            pa = headB if pa is None else pa.next
            pb = headA if pb is None else pb.next
        return pa

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅