剑指offer-链表中倒数第K个结点14

题目描述

输入一个链表,输出该链表中倒数第k个结点。
class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        res=[]
        length=0
        while not head==None:
            res.append(head)
            head=head.next
            length+=1
        if length-k>=0 and k is not 0:
            return res[length-k]
        else:
            return None

思路:还可以设置两个指针,一个先走K歩,相当于设置了一个K长度的尺子,当尺子的右端到达链表尾部时,尺子的左端正好是第K个结点

猜你喜欢

转载自www.cnblogs.com/zhaiyansheng/p/10414790.html