此题思路快慢指针,先用快指针走k步,如果k的大小没有超过链表大小,则快慢指针同时移动,这样两者始终保持k距离,当快指向空时,返回慢指针即为倒数的k个结点
struct ListNode* FindKthToTail(struct ListNode* pHead, int k ) {
if(pHead==NULL)
return NULL;
struct ListNode*fast=pHead,*slow=pHead;
for(int i=0;i<k;i++)
{
if(fast==NULL)
return NULL;
fast=fast->next;
}
while(fast!=NULL)
{
slow=slow->next;
fast=fast->next;
}
return slow;
}
struct ListNode* FindKthToTail(struct ListNode* pHead, int k ) {
if(pHead==NULL)
return NULL;
struct ListNode*fast=pHead,*slow=pHead;
for(int i=0;i<k;i++)
{
if(fast==NULL)
return NULL;
fast=fast->next;
}
while(fast!=NULL)
{
slow=slow->next;
fast=fast->next;
}
return slow;
}