输入一个链表,输出该链表中倒数第K个结点。
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(NULL == pListHead || 0 == k)
return NULL;
ListNode* pFast = pListHead;
ListNode* pSlow = pListHead;
//先让快指针先走k步
while(k--){
if(NULL == pFast)
return NULL;
pFast = pFast->next;
}
//两个指针同时向后移
while(pFast){
pFast = pFast->next;
pSlow = pSlow->next;
}
return pSlow;
}
};
~bye~