输出链表倒数第k个结点

 问题描述:

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

解题思想:

若链表为空或者k为0,则返回的是None。

当链表不为空时,有两种情况:

链表长度n<k时,不存在倒数第k个结点,则返回None。

链表长度n>k时,设置一个长度为k的list,不断地将链表新输入的结点存储进来,若数量超过了k,则把最早进来的抛出,直到最后一个结点,此时list存储的是最后k个结点,输出list中的第一个即可。

# 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 head==None or k==0:
            return None
        temp=[]
        d=0
        while head!=None:
            if len(temp)==k:
                temp.pop(0)
            temp.append(head)
            head=head.next
            d+=1
        if d<k:
            return None
        else:
            return temp[0]
if __name__=="__main__":#输入一个链表,输出该链表中倒数第k个结点。
    a=Solution()
    head=ListNode(0)
    k=head
    for i in range(1,10):
        k.next = ListNode(i)
        k=k.next
    k=head
    while k!=None:
        print k.val
        k=k.next
    print a.FindKthToTail(head,5)

猜你喜欢

转载自blog.csdn.net/noingw96/article/details/84836939