思路:通过反转链表,但是这样的话不好输出单个结点
# -*- 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
pre = None
while head:
first = head.next ##定义新位置
head.next = pre ##将当前位置指向前一个位置
pre = head
head = first
count = 1
while pre:
if count == k:
return pre.val
pre = pre.next
count +=1
利用快慢指针:
class Solution:
def FindKthToTail(self, head, k):
# write code here
slow,fast=head,head
for i in range(k):
if not fast:
return None
fast=fast.next
while fast:
slow=slow.next
fast=fast.next
return slow