160. Intersection of Two Linked Lists --python

题目:

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:


begin to intersect at node c1.


Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

解题:

我们可以定义两个指针,两个指针将两个链表都遍历一遍,那么这两个指针走的总长度是一样的,倘若两个链表相交,那么这两个指针一定会在某个地方相等。为什么会相等呢?

假设 :两个链表:A = {1,3,5,7,9} B = {2,4,7,9},交点是节点'7'。由于链表A的长度5大于链表B的长度是,则链表B会首先到链表的末尾,由于链表B比链表A恰好少走1个节点。通过把链表B指向链表A的头,把链表A指向链表B的头,我们现在让链表B比链表A恰好多走1个节点。所以在第二轮,它们会在交点相等。

class Solution(object):
    def getIntersectionNode(self, headA, headB):

        if not headA or not headB:
            return None
   
        p,q = headA , headB   

        while p != q:   # 当p不等于q时执行下面程序
            p = headB if p is None else p1.next   # 如果p不是none,就取下一个值,是NONE就让p = headB
            q = headA if q is None else q.next    # 如果q不是none,就取下一个值,是NONE就让q = headA
            
        return p1   # p ,q相等有两种情况,一种是相交了,输出相交点,一种是不相交,输出了NONE


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值