python解法

#方法一 用list存储访问倒数第k个 注意存储的是ListNode结点
class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        if not head or k<0 :
               return 
        res=[]
        while head:
                   res.append(head)
                   head=head.next
        return res[-k] if 0<k<=len(res) else None
#方法二快慢指针法 注意k大于链表长度时处理
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindKthToTail(self, head, k):
        if not head or k<0:
            return 
        fast=slow=head
        while k and fast:
            fast=fast.next
            k-=1
        if k>0 and not fast:#注意k大于链表长度时处理
            return 
        while fast:
            fast=fast.next
            slow=slow.next
        return slow
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 17:10
什么素质,我请问呢,要掉小珍珠了。。。又憋屈又生气
苍蓝星上艾露:给它们能的,一群dinner牛马挥刀向更弱者罢了。我写的开源求职AI co-pilot工具,优化你的简历,找到你匹配的岗位,定制你的简历,并让你做好面试准备https://github.com/weicanie/prisma-ai
点赞 评论 收藏
分享
程序员小白条:这比例牛逼,750:1
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务