【剑指Offer 22】链表中倒数第k个节点
/**
* 剑指 Offer 22. 链表中倒数第k个节点
* https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/
*
* 思路:快慢指针
* */
public class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode prev = head;
ListNode next = head;
// next 指针先走 k 步
for (int i = 0; i < k; i++) {
next = next.next;
}
// prev, next 同时移动
while (next != null) {
prev = prev.next;
next = next.next;
}
return prev;
}
}