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:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

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.

 

Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

 

思路很简单,就是长的先走,等持平了之后一起走,判断有没有一样的。

# 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
        a=headA
        A=headA
        b=headB
        B=headB
        
        lena=1
        lenb=1
        while(a.next!=None):
            lena+=1
            a=a.next
        while(b.next!=None):
            lenb+=1
            b=b.next
        minlen=lena
        if(lena!=lenb):
            if(lena<lenb):
                sub=temp=lenb-lena
                minlen=lena
                while(sub):
                    B=B.next
                    sub-=1
            else:
                sub=temp=lena-lenb
                minlen=lenb
                while(sub):
                    A=A.next
                    sub-=1
                
            
        while(minlen):
            if(A.val==B.val):
                return A
            else:
                minlen-=1
                A=A.next
                B=B.next
        return None

刚开始一直纠结python中能不能用a=headA,最后一直提示找不到next,后来发现是因为没有判断是否为空。还有lena的初值,我的判断方式,初值就应该是1,如果判断是当前节点的话,应该是0.。返回结果应该是节点,而不是节点的val。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值