/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(pListHead==nullptr || k <=0 || k>GetLength(pListHead))
return NULL;
ListNode *pFast = pListHead;
ListNode *pSlow = pListHead;
for(int i = 0;i < k-1;i++)
pFast = pFast->next;
while(pFast->next!=nullptr)
{
pFast = pFast->next;
pSlow = pSlow->next;
}
return pSlow;
}
int GetLength(ListNode *pListHead)
{
int length= 0;
while(pListHead)
{
pListHead = pListHead->next;
length++;
}
return length;
}
};
链表中倒数第k个结点
最新推荐文章于 2023-07-26 17:19:47 发布