160.链表的相交节点

我的思路是先计算出两个列表的长度差,然后使用双指针,长的那个先移动,然后再一起移动

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
            p1 = headA
            p2 = headB
            num1,num2,k = 0,0,0
            if not(p1 or p2):     # 判断链表是否为空链表
                return None
            while p1 != None:     # 计算链表p1的长度
                p1 = p1.next
                num1 += 1           
            while p2 != None:     # 计算链表p2的长度
                p2 = p2.next
                num2 += 1
            length = abs(num2-num1)  # 计算两个列表相差多长
            long_length_link = headB    # 找出比较长的链表
            short_length_link = headA
            if num1>num2:
                long_length_link,short_length_link = headA,headB
            p1 = long_length_link
            p2 = short_length_link
            while k < length:     # 长的链表先移动
                p1 = p1.next
                k += 1
            while p2.next != None and p1.next != None:  #  两个链表一起移动
                if p2 == p1:
                    return p1
                p1 = p1.next
                p2 = p2.next
            return None

力扣评论区题解:不过这里如果链表如果不相交,会进入死循环
题解链接

class Solution:
   def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
           p,q = headA,headB
           while q != p:
              # p = p.next if headA else headB
              p = p.next if p else headB
			  q = q.next if q else headA
           return q
Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐