题解 | #链表中倒数第k个结点#
链表中倒数第k个结点
https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(k <= 0 || head==null){//避免空指针异常
return null;
}
ListNode fast = head;
ListNode slow = head;
while(k-1!=0){//fast先走k-1步
fast = fast.next;
if(fast==null){
return null;//fast为空,说明k的值超出链表长度
}
k--;
}
while(fast.next!=null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}