思路:定义两个变量fast和slow,fast先走k-1步,然后一起走,当fast.next==null时,slow指向倒数第k个节点。
代码:
public Node findKTH(int k){
if(head==null){
return null;
}
if(k<1){
throw new RuntimeException("位置错误");
}
Node fast=head;
Node slow=head;
for(int i=0;i<k-1;i++){
if(fast.next!=null){
fast=fast.next;
}else{
throw new RuntimeException("位置错误");
}
}
while(fast.next!=null){
fast=fast.next;
slow=slow.next;
}
return slow;
}