思路:
1.是先访问一便链表,知道链表长度n,返回第n-k个结点
2.注意:链表长度小于k
查找倒数第一个节点:

查找倒数第2个节点

代码
class Solution:
def FindKthToTail(self, head, k):
if not head:
return None
n=0
t = head
while(head):
head = head.next
n=n+1
if k>n:
return None
i=0
mm=n-k
for j in range(n-k):#5-1=4 >>[0~3]4次
t = t.next
return t
nodeNew=Node_l()
nodeNew.tail_insert(5)
nodeNew.tail_insert(6)
nodeNew.tail_insert(7)
nodeNew.tail_insert(8)
nodeNew.tail_insert(9)
nodeNew.travel()
s=Solution()
s.FindKthToTail(nodeNew.head,2)#5,6,7
链表
class Node(object):
def __init__(self,data,next=None):
self.data=data
self.next=next
class Node_l(object):
def __init__(self):
self.head=None
def head_insert(self,data):
node=Node(data)
node.next=self.head#赋值 引用
self.head=node
def tail_insert(self,data):
node=Node(data)
if self.head==None:
self.head=node
else:
cur=self.head
while cur.next!=None:
cur=cur.next
cur.next=node
# print
def travel(self):
if self.head ==None:
return ' '
cur=self.head
while cur!=None:
print (cur.data)
cur=cur.next
return ' '