美文网首页
[Easy] 160. Intersection of Two

[Easy] 160. Intersection of Two

作者: Mree111 | 来源:发表于2019-10-17 13:50 被阅读0次

Description

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

Solution

先找到两个的长度,然后从短的那个length开始一一比较找交点

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        
        Acnt = 0
        Bcnt = 0
        tmp = headA
        
        while tmp is not None:
            tmp = tmp.next
            Acnt+=1
        tmp = headB
        while tmp is not None:
            tmp = tmp.next
            Bcnt+=1
        if Acnt == 0 or Bcnt ==0:
            return None
        smallcnt = min(Acnt,Bcnt)
        largecnt = max(Acnt,Bcnt)
        
        if Acnt < Bcnt:
            small = headA
            large = headB
            
        else:
            small = headB
            large = headA
        for i in range(largecnt-smallcnt):
            large = large.next
        for i in range(smallcnt):
            if small == large:
                return small
            else:
                small = small.next
                large = large.next
        return None

相关文章

网友评论

      本文标题:[Easy] 160. Intersection of Two

      本文链接:https://www.haomeiwen.com/subject/dkbmmctx.html