题解 | #链表中倒数最后k个结点#
链表中倒数最后k个结点
https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
双指针法:定义两个指针temp1和temp2,用指针temp1遍历k个节点,如果在此之前temp1遍历完链表则返回None,
否则,当temp1遍历完k个节点时,temp2从头对链表进行遍历,此时temp1与temp2正好相差k个节点,
所以最后temp1和temp2同时遍历链表,当temp1遍历完时,temp2指向的就是倒数第k个节点。
时间复杂度为O(n),空间复杂度为O(1)
# 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:
temp1, temp2 = pHead, pHead # 定义两个指针
while k != 0:
if temp1 == None:
return temp1
temp1 = temp1.next
k = k-1
temp2 = pHead
while temp1:
temp1 = temp1.next
temp2 = temp2.next
return temp2
