Leetcode刷题记录——剑指 Offer 52. 两个链表的第一个公共节点

在这里插入图片描述
在这里插入图片描述
双指针 各指一个链表的head
同步前进
当一个是None的时候
另一个继续前进 前进K步到None
记录K
然后 双指针重新从各自的头指针开始走
长的 先走K步
而后 两个一起走
相交时即为所求

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

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        cur1 = headA
        cur2 = headB
        while cur1 != None and cur2 != None:
            cur1 = cur1.next
            cur2 = cur2.next
        K = 0#O(1)的空间复杂度
        if cur1 != None:
            while cur1 != None:
                cur1 = cur1.next
                K += 1
                short_ll = headB
                long_ll = headA
        elif cur2 != None:
            while cur2 != None:
                cur2 = cur2.next
                K += 1
                short_ll = headA
                long_ll = headB
        else:
            K = 0
            short_ll = headA
            long_ll = headB
        for i in range(K):
            long_ll = long_ll.next
        while long_ll != short_ll:
            long_ll = long_ll.next
            short_ll = short_ll.next
        return long_ll

猜你喜欢

转载自blog.csdn.net/weixin_41545780/article/details/107551326
今日推荐