欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode160 相交链表

程序员文章站 2022-06-17 19:11:04
...

题目描述

LeetCode160 相交链表

解题

寻找链表相交点用浪漫的解法
A+B=B+A

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        pa = headA
        pb = headB
        flagA = 0
        flagB = 0
        if not pa or not pb:
            return None
        while flagA!=2 and flagB!=2:
            if pa == pb:
                return pa
            if pa.next:
                pa = pa.next
            elif pa.next == None and flagA == 0:
                pa = headB
                flagA = flagA + 1
            elif pa.next == None and flagA ==1:
                flagA = flagA + 1
            if pb.next:
                pb = pb.next
            elif pb.next == None and flagB == 0:
                pb = headA
                flagB = flagB + 1
            elif pb.next == None and flagB ==1:
                flagB = flagB + 1
        return None
相关标签: LeetCode