lintcode练习-380. 两个链表的交叉

380. 两个链表的交叉

请写一个程序,找到两个单链表最开始的交叉节点。

样例

下列两个链表:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

在节点 c1 开始交叉。

挑战

需满足 O(n) 时间复杂度,且仅用 O(1) 内存。

注意事项

  • 如果两个链表没有交叉,返回null
  • 在返回结果后,两个链表仍须保持原有的结构。
  • 可假定整个链表结构中没有循环。

实现思路:

#第一步:得到A,B的长度,和A,B的最后一个节点endA, endB

#第二步:对endA,endB进行判断,如果endA不等于endB,则两个链表没有相交的部分,否则对lenA和lenB进行判断,对长的链表移动|lenA-lenB|

#第三步:两个长度相等的链表一起走,当两个链表第一次相遇时,就到了最开始的交叉点  

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


class Solution:
    """
    @param: headA: the first list
    @param: headB: the second list
    @return: a ListNode
    """
    def getIntersectionNode(self, headA, headB):
        # write your code here
        if headA is None or headB is None:
            return None
        curA, curB = headA, headB
        #第一步:得到A,B的长度,和A,B的最后一个节点endA, endB
        lenA, lenB = 1, 1 
        while curA.next:
            lenA += 1
            curA = curA.next
        
        while curB.next:
            lenB += 1
            curB = curB.next
        
        #第二步:对endA,endB进行判断,如果endA不等于endB,则两个链表没有相交的部分,否则对lenA和lenB进行判断,对长的链表移动|lenA-lenB|
        if curA != curB:
            return None
        curA, curB = headA, headB
        if lenA-lenB > 0:
            for i in range(lenA-lenB):
                curA = curA.next
        else:
            for i in range(lenB-lenA):
                curB = curB.next
        
        #第三步:两个长度相等的链表一起走,当两个链表第一次相遇时,就到了最开始的交叉点    
        while curA != curB:
            curA = curA.next
            curB = curB.next
        
        return curA

        
        
        

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81744501