题解 | #输出单向链表中倒数第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.hasNext()) { // int n = Integer.parseInt(in.nextInt()); int n = in.nextInt(); ListNode head = new ListNode(-1); ListNode temp = head; // 生成链表 for (int i = 0; i < n; i++) { ListNode node = new ListNode(in.nextInt()); temp.next = node; temp = node; } // 定义快慢双指针 ListNode fast = head; ListNode slow = head; // 快指针先走K步 int k = in.nextInt(); for (int i = 0; i < k; i++) { fast = fast.next; } while (fast != null) { slow = slow.next; fast = fast.next; } System.out.println(slow.val); } } } class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; this.next = null; } }
这道题看了别人的解法后自己搞出来了,真的很开心!
快慢双指针太机智了!