《剑指offer》面试题10:链表中倒数第k个节点

题目描述

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

解题思路:

这个题目也延续了剑指offer题目当中信息不给全的传统,其中代码当中的第一个参数head表示链表的表头Node,k表示的是一个数字。我们只需要遍历所有Node,将这些Node放进一个栈当中即可(用列表来代替栈),然后找到栈当中的倒数第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
        #这个k表示的是倒数第k,而不是正数第k
        #k如果比链表的长度还有大的话就返回None
        if head==None or head.next==None:
            return None
        ls=[]
        i=0
        while head:
            ls.append(head)
            head=head.next
        length=len(ls)
        zhengshu=length-k+1
        if k>len(ls) or k<1:#这里还需要考虑k<1的情况,实在是太坑人了
            return None
        else:
            return ls[zhengshu-1]

得解也!

 

posted @ 2020-08-13 14:56  Geeksongs  阅读(157)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.