题目描述:
输入一个链表,输出该链表中倒数第k个结点。
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
p = head
for _ in xrange(k):
if p == None:
return None
else:
p = p.next
while(p):
head = head.next
p = p.next
return head
解析:
单链表只能往后找不能往前找,因此可以先让指针p往后走k个节点,然后head和p同时往后移动,直到p为空为止,head指向的就是倒数第k个节点。