题目描述
输入一个链表,输出该链表中倒数第k个结点。
AC代码:
class Solution:
def FindKthToTail(self, head, k):
# write code here
#将每个节点存在栈里,选取stack中第k个值
stack = []
while head:
stack.append(head)
head = head.next
if k > len(stack) or k <= 0 : return None
for i in range(0, k):
x = stack.pop()
return x
在讨论版中看到了一种使用双指针解题的思路,感觉非常赞,使用python实现如下:
class Solution:
def FindKthToTail(self, head, k):
# write code here
#
p = q = head
i = 0
while p:
if i >= k:
q = q.next
p = p.next
i += 1
if i < k :
return None
return q