跟着专注于计算机视觉的AndyJ的妈妈我学算法之每日一题leetcode160相交链表

相交链表,简单题。但是这个代码,很重要,很简便,这篇博客的代码,要掌握。而且注释的那个细节,也是出错了才察觉到了。所以要注意!争取写简洁的代码。
好了,题目:

160. 相交链表
编写一个程序,找到两个单链表相交的起始节点。

示例 1:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

code:

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        a = headA
        b = headB
        if not headA or not headB: return None
        while a or b:
            if not a:
                a = headB
            if not b:
                b = headA
            if a==b: # 因该先改变a,b然后再比较。不然遇到[1,3],[3]这种用例过不去。
                return a
            a = a.next
            b = b.next
        return None

这么简洁的代码,还是要看看,学学!
好了。

猜你喜欢

转载自blog.csdn.net/mianjiong2855/article/details/107345715
今日推荐