输入一个链表,输出该链表中倒数第k个结点。
由于鲁棒性对软件开发非常重要,所以面试官在招聘的时候对应聘者写出的代码是否鲁棒性非常关注,防御性编程是一种习惯。如果代码不够鲁棒,那么面试官可以找出3中办法让这段代码崩溃。
#-*- 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 head == None or k <= 0:
return None
i, p = 1, head
while i < k:
p = p.next
if p == None:
return None
i += 1
answer = head
while p.next != None:
answer = answer.next
p = p.next
return answer