160. 相交链表

160. 相交链表

题意

找到两个单链表相交的起始节点。

解题思路

分别计算两条链表的长度,接着先让长的链表走两者距离的差,然后再和短的链表一起走,在过程中判断它们的交集。

实现

class Solution(object):
   def getIntersectionNode(self, headA, headB):
       """
      :type head1, head1: ListNode
      :rtype: ListNode
      """
       lenA, lenB = 0, 0
       temp = headA
       while temp:
           temp = temp.next
           lenA += 1
       temp = headB
       while temp:
           temp = temp.next
           lenB += 1
       
       if lenA >= lenB:
           i = 1
           while i <= lenA - lenB:
               headA = headA.next
               i += 1
       else:
           i = 1
           while i <= lenB - lenA:
               headB = headB.next
               i += 1
       
       while headA and headB:
           if headA == headB:
               return headA
           headA = headA.next
           headB = headB.next
           
       return headA
posted @ 2017-09-15 17:35  banananana  阅读(155)  评论(0)    收藏  举报