思路:定义一快一慢两个指针,快指针走 K 步,然后慢指针开始走,快指针到尾时,慢指针就找到了倒数第 K 个节点。 代码实现 代码实现:时间复杂度:O(n),空间复杂度:O(1)
public Node
findKthToTail(Node head
, int k
) {
if(head
== null
|| k
< 1) {
return null
;
}
Node slow
= head
;
Node fast
= head
;
while(k
> 0) {
fast
= fast
.next
;
k
--;
}
while(slow
!= null
&& fast
!= null
) {
slow
= slow
.next
;
fast
= fast
.next
;
}
return slow
;
}
转载请注明原文地址: https://lol.8miu.com/read-31597.html