题解 | 链表中倒数最后k个结点
链表中倒数最后k个结点
https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* FindKthToTail(ListNode* head, int k)
{
// 1、处理边界
if(head==nullptr) return nullptr;
ListNode* cur=head;
int n=0;
while(cur)
{
n++;
cur=cur->next;
}
if(n<k) return nullptr;
// 2、定义快慢指针,两者间隔为k,步长均为1
// 只要fast先走到了空,就返回slow即可!
ListNode* slow=head;
ListNode* fast=slow;
while(k--)
fast=fast->next;
while(fast)
{
slow=slow->next;
fast=fast->next;
}
return slow;
}
};

查看17道真题和解析