输入一个链表,输出该链表中倒数第k个结点。
题目:
输入一个链表,输出该链表中倒数第k个结点。
拙见:
题不难,双指针,考察代码的鲁棒性。
# -*- 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
pre = head
if not pre or k == 0:
return None
while k>1 and pre.next:
k -= 1
pre = pre.next
if k>1:
return None
else:
while pre.next:
head = head.next
pre = pre.next
return head