zoukankan      html  css  js  c++  java
  • leetcode-mid-Linked list-160 Intersection of Two Linked Lists-NO

    mycode 用了反转链表,所以不符合题意

    参考:

    思路:

    1 先让长的链表先走,然后相同长度下看是否相遇

    class Solution(object):
        def getIntersectionNode(self, headA, headB):
            """
            :type head1, head1: ListNode
            :rtype: ListNode
            """
            if not headA or not headB:
                return None
            def cal(head):
                count = 0        
                while head:
                    count += 1
                    head = head.next
                return count
            countA = cal(headA)
            countB = cal(headB)
            plus = countA - countB
            if plus > 0:
                while plus:
                    headA = headA.next
                    plus -= 1
                left = countB
            else:
                plus = abs(plus)
                while plus:
                    headB = headB.next
                    plus -= 1
                left = countA
            while left: #这里无论是headA还是headB都可以啦,因为两个人步伐已经一致啦
                if headA == headB:
                    return headA
                headA = headA.next
                headB = headB.next
                left -= 1
            return None
                    

    2  让短的链表走到头后,再从长链表的头走起,这样当长链表走完后,短链表刚好在长链表上走了长度的差值的步数,所以长链表再从短链表头开始走的时候,相当于两个人起跑线相同啦

    class Solution(object):
        def getIntersectionNode(self, headA, headB):
     
            if not headA or not headB:
                return None
       
            p,q = headA , headB   
     
            while p != q:   # 当p不等于q时执行下面程序
                p = headB if p is None else p1.next   # 如果p不是none,就取下一个值,是NONE就让p = headB
                q = headA if q is None else q.next    # 如果q不是none,就取下一个值,是NONE就让q = headA
                
            return p1   # p ,q相等有两种情况,一种是相交了,输出相交点,一种是不相交,输出了NONE
  • 相关阅读:
    BZOJ2648: SJY摆棋子
    BZOJ1925: [Sdoi2010]地精部落
    BZOJ1941: [Sdoi2010]Hide and Seek
    BZOJ2434: [Noi2011]阿狸的打字机
    BZOJ3295: [Cqoi2011]动态逆序对
    BZOJ1406: [AHOI2007]密码箱
    BZOJ1115: [POI2009]石子游戏Kam
    BZOJ1531: [POI2005]Bank notes
    BZOJ2730: [HNOI2012]矿场搭建
    计算几何《简单》入土芝士
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10967372.html
Copyright © 2011-2022 走看看