题目描述
输入一个链表,输出该链表中倒数第k个结点。
思路
使用相差k个节点的快、慢指针即可,此题麻烦的地方在于边界条件,其他异常情况的考虑
如(不要问我怎么知道这些神奇的测试用例,因为他们都教我做人了,,):
6, {1, 2, 3, 4, 5}
0, {1, 2, 3, 4, 5}
5, {}
想想他们应该输出什么。。。
代码
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindKthToTail(self, head, k):
# write code here
if k == 0 or head == None:
return None
fast = head
slow = head
while fast != None:
if k > 0:
k = k - 1
else:
slow = slow.next
fast = fast.next
return None if k > 0 else slow
高玩的代码
来自牛客网,简单粗暴,简洁,利用了Python里列表的灵活特性
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindKthToTail(self, head, k):
# write code here
res=[]
while head:
res.append(head)
head=head.next
if k>len(res) or k<1:
return
return res[-k]