python剑指offer 链表倒数第k个结点

题目:输入一个链表,输出该链表中倒数第k个结点。

思想:利用两个指针,第一个指针f到达k之后,新建一个指针sencond,遍历最后一个时sencond则为倒数第k个结点

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindKthToTail(self, head, k):
        first = head
#         sencond = head
        length = 0
        if k == 0:
            return 
        while first :
            first = first.next
            length += 1
            if length == k:
                sencond = head
            elif length > k:
                sencond = sencond.next


        if length < k:
            return 
        return sencond

你可能感兴趣的:(数据结构)