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-02 13:52
门头沟学院 Java
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-01 11:27
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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