LeetCode160.Intersection of Two Linked Lists相交链表(Python带测试用例)

一、题目

编写一个程序,找到两个单链表相交的起始节点。

二、思路

A和B两个链表长度可能不同,但是A+B和B+A的长度是相同的,所以遍历A+B和遍历B+A一定是同时结束。
如果A,B相交的话A和B有一段尾巴是相同的,所以两个遍历的指针一定会同时到达交点 如果A,B不相交的话两个指针就会同时到达A+B(B+A)的尾节点。

三、题解

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None



def make_list(arr):
    head_node = None
    p_node = None
    for a in arr:
        new_node = ListNode(a)
        if head_node is None:
            head_node = new_node
            p_node = new_node
        else:
            p_node.next = new_node
            p_node = new_node
    return head_node

# def print_list(head):
#     while head is not None:
#         print(head.val, end=',')
#         head = head.next

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        # curr1指向链表A的头结点,curr2指向链表B的头结点
        curr1, curr2 = headA, headB
        while curr1 != curr2:
            # curr1 = curr1.next if curr1 else headB
            if curr1:
                curr1 = curr1.next
            else:
                # 当 curr1 到达链表的尾部时,将它重定位到链表 B 的头结点
                curr1 = headB
            # curr2 = curr2.next if curr2 else headA
            if curr2:
                curr2 = curr2.next
            else:
                # 当 curr2 到达链表的尾部时,将它重定位到链表 A 的头结点。
                curr2 = headA

        return curr1
"""
A和B两个链表长度可能不同,但是A+B和B+A的长度是相同的,所以遍历A+B和遍历B+A一定是同时结束。 
如果A,B相交的话A和B有一段尾巴是相同的,所以两个遍历的指针一定会同时到达交点 如果A,B不相交的话两个指针就会同时到达A+B(B+A)的尾节点
"""
s = Solution()
a = [4,1,8,4,5]
b = [5,6,1,8,4,5]
head_a = make_list(a)
head_b = make_list(b)

# 在8处相交
head_a.next.next = head_b.next.next.next

# print_list(head_a)

# print_list(head_b)
print(s.getIntersectionNode(head_a,head_b))

时间复杂度 : O(m+n)
空间复杂度 : O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值