题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
import java.util.*; class ListNode { ListNode next; int val; public ListNode() { } public ListNode(int val) { this.val = val; } } public class Main { //使用双指针,快指针指向第k个节点,慢指针指向第一个节点,一起向下遍历 public static void main(String[] args) { ListNode node = new ListNode(); ListNode head = node; Scanner sc = new Scanner(System.in); while (sc.hasNext()) { int n = sc.nextInt(); for (int i = 1; i <= n; i++) { ListNode tmp = new ListNode(sc.nextInt()); node.next = tmp; node = node.next; } int k = sc.nextInt(); ListNode slow = head, quick = head; while (k-- != 0) { if (quick.next == null) { System.out.println(-1); return; } quick = quick.next; } while (quick != null) { slow = slow.next; quick = quick.next; } System.out.println(slow.val); } } }