题目描述
输入一个链表,输出该链表中倒数第k个结点。
解题思路
循环将链表的所有结点存下来,对于有效的k直接取出对应结点即可。
代码
Python(2.7.3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20# -*- 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