8.输入一个链表,输出该链表中倒数第k个结点。
倒数第K个结点就是正数第n-k+1个结点,下标为n-k。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
def FindKthToTail(self, head, k):
# write code here
stack1=[]
p1 = head
if not p1:
return None
else:
while p1:
stack1.append(head)
p1=p1.next
if k>len(stack1):
return None
else:
return stack1[len(stack1)-k]
快慢指针
两个指针,先让第一个指针和第二个指针都指向头结点,然后再让第一个指正走(k-1)步,到达第k个节点。然后两个指针同时往后移动,当第一个结点到达末尾的时候,第二个结点所在位置就是倒数第k个节点了。
# -*- 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
p = head
q = head
n = 0
while p:
if n>=k:
q=q.next
n +=1
p = p.next
return q if k<=n else None