# 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
if not cur:
return None
length = 0
#解法1:将链表所有数值全部取到列表中,然后把-k到-1的列表元素提取出来新建一个链表返回。
# list1 = []
# pre = post = ListNode(0)
# while cur:
# length += 1
# list1.append(cur.val)
# cur = cur.next
# if length < k:
# return None
# i = -k
# while -k <= i and i <= -1:
# post.next = ListNode(0)
# post.next.val = list1[i]
# post = post.next
# i += 1
# return pre.next
#解法2:先遍历链表长度,当遍历长度length-k次后,然后当前指针指向的子链表即可
while cur:
length = length + 1
cur = cur.next
if length < k:
return None
a = length - k
if a == 0:
return pHead
cur = pHead
i = 0
while cur:
i = i + 1
cur = cur.next
if a == i:
return cur