{面试题15: 链表中倒数第 k 个节点}

From 剑指Offer 何海涛 著

#include <iostream>

struct ListNode {
    int m_nValue;
    ListNode *m_pNext;
};

ListNode* findKthToTail(ListNode *head, unsigned int k) {
    ListNode *first = head;
    ListNode *second = head;
    unsigned int num = 0;
    while(num < k && first != NULL) {
        first = first->m_pNext;
        num++;
    }
    if(num < k) { // 不能用 first == NULL 来代替, 因为 first == NULL 无法区分 num < k, num == k 两种情况
        return NULL;
    }
    while(first != NULL) {
        first = first->m_pNext;
        second = second->m_pNext;
    }
    return second;
}

测试集:

void test(ListNode *head, unsigned int k, ListNode *expected) {
    std::cout << std::boolalpha << (findKthToTail(head, k)== expected) << std::endl;
}

int main(int argc, char* argv[]) {
    ListNode node1 = {1, NULL};
    ListNode node2 = {2, &node1};
    ListNode node3 = {3, &node2};
    ListNode node4 = {4, &node3};
    ListNode node5 = {5, &node4};
    
    test(NULL, 0, NULL);
    test(NULL, 2, NULL);

    test(&node5, 0, NULL);
    test(&node5, 1, &node1);
    test(&node5, 3, &node3);
    test(&node5, 4, &node4);
    test(&node5, 5, &node5);
    test(&node5, 6, NULL);
    
    return 0;

}

 

posted @ 2015-04-18 23:19  long#long  阅读(127)  评论(0编辑  收藏  举报