链表中倒数第k个结点

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

solution:

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        if head is None or k<1:
            return None
        work = head
        while k>1 and work is not None:
            work = work.next
            k -= 1
        if work is None:
            return work
        while work.next is not None:
            work = work.next
            head = head.next
        return head
posted @ 2019-07-12 21:19  bernieloveslife  阅读(100)  评论(0编辑  收藏  举报