题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNextInt()){ int n = in.nextInt(); int i = 1; ListNode head = new ListNode(-1);//创建一个头结点 ListNode headNode = head; //创建链表 for (int j = 0; j < n; j++) { ListNode node = new ListNode(in.nextInt()); head.next = node; head = node; } int num = in.nextInt(); //定义一前一后两指针,让前面的指针与后面的指针相差指定的num //现在head就在我们最后一个节点,但是haedNode是第一个我们的头结点 ListNode first = headNode; for (int j = 0; j < n-num+1; j++) { first = first.next; } System.out.println(first.val); } in.close(); } } class ListNode { int val; ListNode next; public ListNode(int val) { this.val = val; } public ListNode(int val, ListNode next) { this.val = val; this.next = next; } }