题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner fzhinput = new Scanner(System.in);
while(fzhinput.hasNext()){
int jdnum = fzhinput.nextInt();
ListNode head = null;
ListNode tail = null;
for(int i=0;i<jdnum;i++){
int value = fzhinput.nextInt();
ListNode lbsz = new ListNode(value);
if (head == null) {
head = lbsz;
tail = lbsz;
} else {
tail.zzhen = lbsz;
tail = lbsz;
}
}
int k = fzhinput.nextInt();
ListNode result = findKToTail(head,k);
if(result!=null){
System.out.println(result.zkey);
}
else{
System.out.println("null");
}
}
}
public static ListNode findKToTail(ListNode head,int k){
if(head==null||k<=0){
return null;
}
ListNode fast = head;
ListNode slow = head;
for(int i=0;i<k;i++){
if(fast!=null){
fast=fast.zzhen;
}
else{
return null;
}
}
while(fast!=null){
fast=fast.zzhen;
slow=slow.zzhen;
}
return slow;
}
}
class ListNode{
int zkey;
ListNode zzhen;
ListNode(int z){
zkey=z;
zzhen=null;
}
}
