题目描述
输入一个链表,输出该链表中倒数第K个结点。
基本思想
设置两个指针fast和slow。fast先走K-1步,再让fast和slow同时走,直到fast.next为None(走到头),此时slow指向倒数第K个结点。
Python
class Solution:
def FindKthToTail(self, head, k):
# write code here
if not head or k <= 0:
return None
slow = fast = head
if k > 1:
for _ in range(k-1):
fast = fast.next
if not fast:
return None
while fast.next is not None:
fast = fast.next
slow = slow.next
return slow
关于while not A和while A is not None
判断对象是否有定义,要用A is None判断
判断对象是否为空,可以用not A 和A is None判断
此处显然是判断next是否有节点,必须用is not None
参考文档1:https://blog.csdn.net/johinieli/article/details/80141757
参考文档2:https://blog.csdn.net/qq_31829611/article/details/89277560
网友评论