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

本内容为牛客网,剑指off题目:链表中倒数第k个节点

# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 21:21:40 2019

@author: Administrator
输入一个链表,输出该链表中倒数第k个结点。
本解法没有考虑到k的值超过了链表的最大长度
"""
class ListNode:
    def __init__(self,x):
        self.val = x
        self.next = None

class Solution:
    def FindKthToTail(self,head,k):
        first,second = head,head    #定义两个地址分别存放间距为k的节点地址
        for i in range(k):  #先从头指到第k个节点位置
            second = second.next
        while second:   #两个节点依次运行,直到尾节点结束
            first = first.next
            second = second.next
        return first

if __name__ == '__main__':
    n = ListNode(1)
    n2 = ListNode(2)
    n3 = ListNode(3)
    n4 = ListNode(4)
    n5 = ListNode(5)
    
    n4.next = n5
    n3.next = n4
    n2.next = n3
    n.next = n2
    solution = Solution()
    result = solution.FindKthToTail(n,3)
    while True:
        print(result.val)
        result = result.next
        if result == None:
            break
原文地址:https://www.cnblogs.com/missidiot/p/10523005.html