题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
import java.util.Scanner; import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList<Integer> listLengths = new ArrayList<>();// 存放多组数据 ArrayList<int[]> listSums = new ArrayList<>(); ArrayList<Integer> kLengths = new ArrayList<>(); int num = 0; boolean flag = true; while (sc.hasNextLine()) { // 等待控制台,是否有输入 String s = sc.nextLine().trim();// 获取输入 if (Objects.equals(s, "")) { break; } if (num % 3 == 0) { listLengths.add(Integer.parseInt(s)); } else if (num % 3 == 1) { listSums.add(Arrays.stream(s.split(" ")).mapToInt(Integer::parseInt).toArray()); } else { kLengths.add(Integer.parseInt(s)); } num++; // 变量存放位置 } // int length = 8; // int[] arr = new int[]{1,2,3,4,5,6,7,8}; // int k = 4; for (int i = 0; i < listLengths.size(); i++) { int length = listLengths.get(i); int[] arr = listSums.get(i); Integer k = kLengths.get(i); System.out.println(lastKValue(length, arr, k)); } } private static Integer lastKValue(int length, int[] arr, int k) { if (length == 1) { return arr[0]; } ListNode listNode = new ListNode(); ListNode dumy = listNode; //拷贝地址 for (int i = 0; i < length; i++) { listNode.next = new ListNode(arr[i]); listNode = listNode.next; } ListNode cur = dumy.next; // 输出倒数第K个节点,也就是顺数的 length-k,索引位置就是length-k-1 ListNode res = null; for (int i = 0; i < length - k; i++) { res = cur.next; cur = res; } return res.value; } static class ListNode { Integer value; ListNode next; public ListNode(Integer value, ListNode next) { this.value = value; this.next = next; } public ListNode(Integer value) { this.value = value; } public ListNode() { } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } public ListNode getNext() { return next; } public void setNext(ListNode next) { this.next = next; } } }