链表中倒数第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 || k>GetLength(pListHead))  
            return NULL;  
          
        ListNode *pFast = pListHead;  
        ListNode *pSlow = pListHead;  
          
        for(int i = 0;i < k-1;i++)  
            pFast = pFast->next;  
          
        while(pFast->next!=nullptr)  
        {  
            pFast = pFast->next;  
            pSlow = pSlow->next;  
        }  
          
        return pSlow;  
    }  
      
    int GetLength(ListNode *pListHead)  
    {  
        int length= 0;  
        while(pListHead)  
        {  
            pListHead = pListHead->next;  
            length++;  
        }  
        return length;  
    }  
};  

 

posted on 2017-03-01 17:59  123_123  阅读(95)  评论(0编辑  收藏  举报