经典题目
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pHead, int k) {
if (k <= 0 || pHead == nullptr) { // 边界
return nullptr;
}
ListNode *fast = pHead, *slow = pHead;
for (int i = 1; i < k && fast; i++) {
fast = fast->next;
}
if (fast == nullptr) {
return nullptr;
}
while (fast->next) {
fast = fast->next;
slow = slow->next;
}
return slow;
}
};