#方法一 用list存储访问倒数第k个 注意存储的是ListNode结点
class Solution:
def FindKthToTail(self, head, k):
# write code here
if not head or k<0 :
return
res=[]
while head:
res.append(head)
head=head.next
return res[-k] if 0<k<=len(res) else None
#方法二快慢指针法 注意k大于链表长度时处理
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindKthToTail(self, head, k):
if not head or k<0:
return
fast=slow=head
while k and fast:
fast=fast.next
k-=1
if k>0 and not fast:#注意k大于链表长度时处理
return
while fast:
fast=fast.next
slow=slow.next
return slow