链表中倒数第k个结点
题目描述:输入一个链表,输出该链表中倒数第k个结点
使用两个变量指向链表的第一个和第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
if head is None:
return None
elif k == 0:
return None
else:
nodeK = head
k = k - 1
while k >0 and nodeK is not None:
k = k-1
nodeK = nodeK.next
if nodeK is None:
return None
else:
node0 = head
while nodeK is not None and nodeK.next is not None:
node0 = node0.next
nodeK = nodeK.next
return node0
需要注意的是
链表为空,返回空
k的取值范围,超过链表的范围返回空
Pythonic写法
# -*- 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
temp = []
while head is not None:
temp.append(head)
head = head.next
if k > 0 and k <= len(temp):
return temp[-k]
return None
Java和C++可以使用栈来实现