用两个指针,指针ahead先出发k-1步,当ahead到达链表尾节点的时候,behind指针刚好到达倒数第k个节点
但是要注意以下情况:

  • 输入的head为空指针
  • 输入的链表长度小于k
  • k = 0
    class Solution:
     def FindKthToTail(self, head, k):
         # write code here          
         if not head or k == 0:
             return None #注意这里要返回None,而不是False,才能通过
         ahead = head
         behind = head 
         for i in range(k-1):
             if not ahead.next:
                 return None 
             else:
                 ahead = ahead.next
         while ahead.next:
             ahead = ahead.next
             behind = behind.next
         return behind