题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
双指针解决输出链表倒数第k个节点
import java.io.IOException; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); while(sc.hasNext()){ int count = sc.nextInt(); // 哨兵节点 Node dummy = new Node(-1); Node cur = dummy; for(int i = 0; i < count; i++){ // 正向构建链表 cur.next = new Node(sc.nextInt()); cur = cur.next; } Node before = dummy.next; int k = sc.nextInt(); // before先走k-1步 for(int i = 1; i < k; ++i){ before = before.next; } // 然后after再走 Node after = dummy.next; while(before.next != null){ before = before.next; after = after.next; } System.out.println(after.value); } } private static class Node{ public int value; public Node next; public Node(int value) { this.value = value; } } }