问题描述:输入一个链表,输出该链表中倒数第k个结点。
思路分析:
我们使用两个指针来进行处理,两个指针间隔为k-1,同时在链表上移动,这样第一个指针到达列表末尾的时候第二个指针刚好指向倒数第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
if head == None or k <= 0:
return None
ptr2 = head
ptr1 = head
while k > 1:
if ptr2.next != None:
ptr2 = ptr2.next
k -= 1
else:
return None
while ptr2.next != None:
ptr1 = ptr1.next
ptr2 = ptr2.next
return ptr1