题解 | #链表中倒数第k个结点#
链表中倒数第k个结点
https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head, int k) {
if (k <= 0) {
return null;
}
if (head == null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
int count = 0;
while (count != k - 1) {
if (fast.next != null) {
fast = fast.next;
count++;
} else {
return null;
}
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
查看14道真题和解析