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
全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 13:32
点赞 评论 收藏
分享
仁者伍敌:难怪小公司那么挑剔,让你们这些大佬把位置拿了
点赞 评论 收藏
分享
有没有佬投这个呀,怎么样呀求问
投递中科院空天信息创新研究院等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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