leetcode 160.相交链表

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

如下面的两个链表

在节点 c1 开始相交。


示例 1:

输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8


输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

注意:

  • 如果两个链表没有交点,返回 null.
  • 在返回结果后,两个链表仍须保持原有的结构。
  • 可假定整个链表结构中没有循环。
  • 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。

普通解法(双指针):

# 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
        """
        if headA == None or headB == None:
            return None
        head1 = headA
        head2 = headB
        while(head1.next != None and head2.next != None):
            head1 = head1.next
            head2 = head2.next
        dis = 0
        head3 = head1.next if head1.next != None else head2.next
        longerOne = 1 if head1.next != None else 2
        while(head3 != None):
            head3 = head3.next
            dis += 1
        head1 = headA
        head2 = headB
        for i in range(dis):
            if longerOne == 1:
                head1 = head1.next
            else:
                head2 = head2.next
        while (head1 != None and head2 != None):
            if head1 == head2:
                return head1
            head1 = head1.next
            head2 = head2.next
        return None

这种链表解法常用双指针,两个指针分别从链表的头部出发,向后遍历,速度都为1。此时必然有一个指针率先到达链表的末尾,而另一指针距离抵达末尾的距离就是两个链表的长度差。在一次完整的遍历链表之后我们就获得了两个链表的长度差n。我们让长的那个链表指针先前进n个节点,随后两个指针再一起前进,如果两个链表有相交,那么两个指针必然会相遇,相遇的节点就为相交的交点。该解法时间复杂度为O(n),空间复杂度为O(1)

链表拼接:

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if not headA or not headB:
            return None
        nodeA = headA
        nodeB = headB
        while(nodeA !=nodeB):
            nodeA = nodeA.next if nodeA else headB
            nodeB = nodeB.next if nodeB else headA
        return nodeA

假设两个链表相交且链表1的长度为a+c,链表2的长度为b+c(所以c为两个链表的相交部分)。设置两个链表的指针,指针每次前进一步,当走到末尾指针指向另一个链表的头部继续出发。如指针A从链表1的头部出发,走到末尾后指向链表2的头部继续出发。如果两个链表相交,那么最后两个指针必定会相遇,相遇时指针A走过的路径为a+c+b,指针B走过的路径为b+c+a,明显两个路径的长度相等,所以他们必定在此点相交。

微信图片_20200419110414.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值