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

class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        if(pListHead == nullptr) return nullptr;
        int len = 0;
        ListNode* root = pListHead;
        while(pListHead != nullptr){
            len++;
            pListHead = pListHead->next;
        }
        int counter = len - k;
        if(counter < 0) return nullptr;
        while(root != nullptr){
            if(counter == 0) return root;
            root = root->next;
            counter--;
        }
        return nullptr;
    }
};

posted @ 2018-08-25 18:44  一条图图犬  阅读(91)  评论(0编辑  收藏  举报