题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
import java.util.*;
import java.io.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String str = null;
while((str=bf.readLine())!=null){
//获取原始输入
int len = Integer.parseInt(str);
String[] num = bf.readLine().split(" ");
int want = Integer.parseInt(bf.readLine());
//创建链表头节点
ListNode ls = new ListNode();
//头插法将新节点插入链表头
for(int i=0;i<len;i++){
ListNode newC = new ListNode(Integer.parseInt(num[i]),ls);
//更新头节点
ls = newC;
}
//从头开始遍历链表直至满足条件
while(ls!=null && want !=1){
ls = ls.next;
want--;
}
//输出对应节点
System.out.println(ls.num);
}
}
}
//自定义链表节类
class ListNode {
int num;
ListNode next;
public ListNode(){}
public ListNode(int l,ListNode n){
this.num=l;
this.next =n;
}
}


查看24道真题和解析