题解 | #输出单向链表中倒数第k个结点#
看到好多解答完全不看题目要求的,鄙人自荐解题思路。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
int a = Integer.valueOf(in.nextLine());
//第一行,也就是链表长度
String s = in.nextLine();
Scanner sc = new Scanner(s);
//第二行,每个链表节点
int c = Integer.valueOf(in.nextLine());
//第三行,c
ListNode headNode = new ListNode(-1);
ListNode temp = headNode;
while (a > 0) { // 正序构建链表
int b = sc.nextInt();
temp.next = new ListNode(b);
temp = temp.next;
if (a == c) {//返回倒数第c个结点指针
System.out.println(temp.key);
}
a--;//构建后要忘记链表长度
}
}
}
}
class ListNode {
Integer key;
ListNode next;
// 有参构造函数
public ListNode(Integer key) {
this.key = key;
this.next = null;//异常返回空指针
}
}
安克创新 Anker公司福利 911人发布