程序员面试金典 2.2 链表中倒数第k个结点

题目

输入一个链表,输出该链表中倒数第k个结点。

我的题解

class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        ListNode* fast = pListHead;
        ListNode* slow = pListHead;
        int count = 0;
        while(fast != NULL) {
            count ++;
            fast = fast->next;
            if(count > k)
                slow = slow->next;
        }
        if(count <= (k - 1)) return NULL;
        return slow;
    }
};

你可能感兴趣的:(Algorithm,程序员,链表,面试)