题目描述:

输入一个链表,输出该链表中倒数第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) return nullptr;
        ListNode *pAhead = pListHead;
        ListNode *pBehind = nullptr;
        for(int i=0;i<k-1;++i){
            if(pAhead->next)
                pAhead = pAhead->next;
            else
                return nullptr;
        }
        pBehind = pListHead;
        while(pAhead->next){
            pAhead = pAhead->next;
            pBehind = pBehind->next;
        }
        return pBehind;
    }
};

如有建议或其他问题,可随时给我们留言。或者到以下链接:

https://github.com/gaobaoru/code_day

Star/Fork/Push 您的代码,开源仓库需要您的贡献。

请查看Coding 题目网址和收藏Accepted代码仓库,进行coding!!!