面試題22:輸入一個鏈表,輸出該鏈表中倒數第k個結點。
/*
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) //如果頭指針爲空或者返回倒數第0個節點,則返回空指針
return nullptr;
ListNode* pAhead = pListHead;
ListNode* pBehind = pListHead;
for(unsigned int i = 0; i < k - 1; ++i){
if (pAhead->next == nullptr) //如果K大於鏈表長度,則返回空指針
return nullptr;
pAhead = pAhead->next;
}
while(pAhead->next != nullptr){
pAhead = pAhead->next;
pBehind = pBehind->next;
}
return pBehind;
}
};