Skip to the content.

链表中倒数第k个结点


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


来自牛客 剑指offer

题目描述

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

ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
    int count = 0;
    auto head = pListHead;
    while (pListHead) {
        pListHead = pListHead->next;
        ++count;
    }
    if (count < k) {
        return NULL;
    }
    int step = count - k;
    while (step--) {
        head = head->next;
    }
    return head;
}