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

题目描述

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

思路

定义2个指针,快指针比慢指针多遍历k个结点。那么,快指针指到链表尾的时候,慢指针所指的位置就是链表的倒数第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 not head:
            return None
        current = head
        count = k
        while count >0:
            if current:
                current = current.next
            else:
                return None
            count-= 1 
        while current:
            head = head.next 
            current = current.next
        return head
原文地址:https://www.cnblogs.com/wangzhihang/p/11790739.html