关键在于:了解单项链表结构。
另外有问题需要进一步学习:值传递与引用传递。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNextInt()) {
int n = scan.nextInt();
//定义表头
ListNode headNode = new ListNode(-1);
ListNode temp = headNode;
//建立单项链表
for (int i = 0; i < n; i++) {
int value = scan.nextInt();
temp.nextNode = new ListNode(value);
temp = temp.nextNode;
}
//获得倒数k值
int k = scan.nextInt();
for (int i = 0; i < n - k + 1;
i++) { //倒数第k个,即为顺数第n-k+1个,序号则为n-k
headNode = headNode.nextNode;
}
//输出
System.out.println(headNode.value);
}
}
}
class ListNode {
Integer value;
ListNode nextNode;
ListNode() {};
ListNode(Integer value) {
this.value = value;
this.nextNode = null;
}
}