鏈表中倒數第K個節點

面試題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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章