题目描述:
输入一个链表,输出该链表中倒数第k个结点。
主要思想 :
代码实现 :
public static ListNode FindKthToTail(ListNode head, int k) {
ListNode fast = head;
ListNode slow = head;
if (head == null) {
return null;
}
if(k == 0 ){
return null;
}
for (int i = 1; i <= k - 1; i++) {
if (fast.next == null) {
return null;
}
fast = fast.next;
}
while (fast.next!= null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
注意点 :
- 需要判断head是否为空,若空返回null
- 需要判断k是否为0,若为0返回null