相当简单了,直接得到链表长度,然后长度小于k时,返回None,长度大于等于k时,链表移动到长度-k个node,然后返回就行。
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pHead ListNode类
# @param k int整型
# @return ListNode类
#
class Solution:
def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
# write code here
cur = pHead
size=0
while cur:
size+=1
cur=cur.next
# print(size)
if size<k:
return None
else:
ind = size - k
cur=pHead
for i in range(ind):
cur = cur.next
return cur
head=ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
print(Solution().FindKthToTail(head,2).val)