输入一个长度为 n 的链表,设链表中的元素的值为 ai ,返回该链表中倒数第k个节点。
如果该链表长度小于k,请返回一个长度为 0 的链表。
双指针。slow 指针和 fast 指针保持k的间距,当 fast 为 null 时slow即为答案。
代码
class Solution {
public:
ListNode* FindKthToTail(ListNode* pHead, int k) {
// write code here
ListNode* slow = pHead;
ListNode* fast = pHead;
for(int i = 0; i < k; ++i)
{
if(fast==NULL)
{
return nullptr;
}
fast = fast->next;
}
while(slow and fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
};



