題目:
輸入一個鏈表,輸出該鏈表中倒數第k個結點。AC的代碼:
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(pListHead==NULL)return NULL;
int sum=1,sum1=1;
ListNode *Node=pListHead;
while(Node->next!=NULL){
sum+=1;
Node=Node->next;
}
if(k==1)return Node;//如果是最後一個節點
Node=pListHead;
while(Node->next!=NULL){
if(sum1==sum-k+1)return Node;
Node=Node->next;
sum1+=1;
}//如果是其他節點
return NULL;
}
};
- 劍指Offer上的代碼
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if (pListHead == NULL || k == 0)return NULL;
ListNode* pAhead = pListHead;
ListNode* pBehind = NULL;
for (unsigned int i = 0; i < k - 1; i++){
if (pAhead->next!=NULL)
pAhead = pAhead->next;
else return NULL;
}
pBehind = pListHead;
while (pAhead->next != NULL){
pAhead = pAhead->next;
pBehind = pBehind->next;
}
return pBehind;
}//只需遍歷一遍
};