题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
单向节点比较简单,不需要设置head,hail等节点。只需要按需将数据封装成node节点。并根据总长度推测出倒数第K节点在长度N上的顺时针,遍历查询出来即可
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case int n = in.nextInt(); ListNode node = new ListNode(); for (int i=0;i<n;i++) { node.add(in.nextInt()); } //按照顺时针计算index int index = n -in.nextInt(); // 遍历node节点 int count = 0; ListNode res = node; while (count<index) { res = res.next; count++; } System.out.println(res.key); } } static class ListNode { int key; ListNode next; ListNode() { } ListNode(int num) { this.key = num; } public void add(int num) { if (key ==0) { this.key=num; } else { // 不等于0时表示头节点已经有数据了 ListNode p = this; while (p.next!=null) { p = p.next; } // 封装成一个node节点 p.next = new ListNode(num); } } } }