剑指offer-链表中倒数第K个结点

这个题貌似经常听说?

两个指针,指针1指向头,指针2指向头+k的位置,指针2到达尾部的时候指针1就是答案

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        ListNode* ph = pListHead, *pf = pListHead;
        for(int i = 0; ph && i < k - 1; ++i){
            ph = ph->next;
        }
        if(ph == nullptr)
            return nullptr;
        while(ph->next){
            ph = ph->next;
            pf = pf->next;
        }
        return pf;
    }
};
View Code

 

posted @ 2017-10-13 18:25  Deaglepc  阅读(122)  评论(0编辑  收藏  举报