书中方法:用两个节点一次遍历求得倒数第k个节点。注意头节点为空,k<=0,k大于节点个数的情况。
public ListNode find(ListNode head, int k){
if(head == null || k <=0){
return null;
}
ListNode first = head, second = head;
for(int i=1; i<=k; i++){
//如果k超出了节点的个数
if(first == null){
return null;
}else{
first = first.next;
}
}
while(first != null){
first = first.next;
second = second.next;
}
return second;
}