题目描述
题解
快慢指针,想知道倒数第k个,我们就让快指针先走k步,然后慢指针在开始走,当快指针走到最后的时候,这时慢指针所指的,就是倒数第K个节点。
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode fast = head, slow = head;
for (int i = 0; i < k; i++){
fast = fast.next;
}
while (fast != null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}