#面试题22. 链表中倒数第k个节点
难度:简单
题目描述
解题思路
经典的快慢指针
/*
* 面试题22. 链表中倒数第k个节点
* 2020/5/14
* 快慢指针思想 快指针先前进k个,再同步前进,这样当快指针到达终点的时候,慢指针就指向倒数第k个
*/
public ListNode getKthFromEnd(ListNode head, int k) {
if(head == null)
return head;
ListNode fast = head,slow = head;
while(k-- > 0) {
fast = fast.next;
}
while(fast != null) {
slow = slow.next;
fast = fast.next;
}
return slow;
}