题解 | #链表中倒数第k个结点#
链表中倒数第k个结点
http://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a
/*
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(head == null || k < 0)
return null;
ListNode slow = head;
ListNode fast = head;
while (k > 0){
k--;
if(fast == null) //如果k过大,fast可能已经是null了,所以每次循环都要判断一下fast是否为空,防止出现空指针异常
return null;
fast = fast.next;
}
while(fast != null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
查看14道真题和解析