题解 | #输出单向链表中倒数第k个结点#
输出单向链表中倒数第k个结点
https://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d
import java.util.Scanner; class ListNode { int m_nKey; ListNode m_pNext; ListNode(int val) { m_nKey = val; m_pNext = null; } } public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int n = scanner.nextInt(); // 链表结点个数 ListNode head = new ListNode(scanner.nextInt()); // 构建头结点 ListNode cur = head; for (int i = 1; i < n; i++) { cur.m_pNext = new ListNode(scanner.nextInt()); cur = cur.m_pNext; } int k = scanner.nextInt(); // 倒数第k个结点 ListNode result = findKthToTail(head, k); System.out.println(result != null ? result.m_nKey : "空指针异常"); } scanner.close(); } // 寻找倒数第k个结点 public static ListNode findKthToTail(ListNode head, int k) { if (head == null || k <= 0) return null; ListNode slow = head; ListNode fast = head; // 让快指针先走k步 for (int i = 0; i < k; i++) { if (fast == null) return null; // 如果链表长度小于k,返回null fast = fast.m_pNext; } // 快慢指针一起走,直到快指针到达链表尾部 while (fast != null) { slow = slow.m_pNext; fast = fast.m_pNext; } return slow; // 返回倒数第k个结点 } }