链表相交python(leetcode02.07)

#面试题 02.07. 链表相交

#两种方法

#给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果#两个链表没有交点,返回 null 

 #1 先计算长度的方法

# 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:
        cur_A, cur_B = headA, headB
        # 分别计算headA和headB的长度
        def ListNode_length(head:ListNode):
            L = 0
            while (head != None):
                head = head.next
                L += 1
            return L
        L_A, L_B = ListNode_length(headA), ListNode_length(headB)

        if L_A >= L_B:
            step = L_A - L_B
        else:
            step = L_B - L_A
            temp = cur_A
            cur_A, cur_B = cur_B, temp

        for _ in range(step):
            cur_A = cur_A.next
        while(cur_A !=cur_B):
            cur_A, cur_B = cur_A.next, cur_B.next

        return cur_A

#2 两个链表相接的方法

# 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
        """
        cur_A, cur_B = headA, headB

        while(cur_A != cur_B):
            cur_A = cur_A.next if cur_A != None else headB
            cur_B = cur_B.next if cur_B != None else headA
        return cur_A

        #两个链表不相等时,当慢指针循环结束短链表后,慢指针接着循环长链表
        #快指针同理
        #两个指针终会相遇在相交的节点

Guess you like

Origin blog.csdn.net/ziqingnian/article/details/121906787