本文首发于我的个人博客Suixin’s Blog
原文: https://suixinblog.cn/2019/03/target-offer-linked-list-kth-node-to-tail.html 作者: Suixin
题目描述
输入一个链表,输出该链表中倒数第k个结点。
解题思路
循环将链表的所有结点存下来,对于有效的k直接取出对应结点即可。
代码
Python(2.7.3)
# -*- 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 k < 1:
return
nodes = []
cur = head
while cur is not None:
nodes.append(cur)
cur = cur.next
if k > len(nodes):
return
else:
return nodes[-k]
运行时间:25ms
占用内存:5728k
网友评论