/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <list>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* FindKthToTail(ListNode* pHead, int k)
{
// 一个指针走k步
ListNode* cur = pHead;
ListNode* pre = pHead;
for(int i=0;i<k;i++)
{
if(cur==nullptr) return nullptr;
cur=cur->next;
}
// 另一个指针开始走
while(cur!=nullptr)
{
cur=cur->next;
pre=pre->next;
}
return pre;
}
};
双指针解决倒数的问题
如果cur==nullptr, 此时for循环还没有停止, 可想而知链表的长度<k.
直接返回nullptr

京公网安备 11010502036488号