面试题22:链表中倒数第k个节点

考察链表的操作,注意使用一次遍历。相关题目:求链表的中间节点。

C++版

#include <iostream>
#include <algorithm>
using namespace std;

// 定义链表
struct ListNode{
    int val;
    struct ListNode* next;
    ListNode(int val):val(val),next(nullptr){}
};

// 返回倒数第k个节点
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
    if(pListHead == nullptr || k == 0)
        return nullptr;
    ListNode* pAhead = pListHead;
    ListNode* pBehind = nullptr;
    for(unsigned int i = 0; i < k-1; i++){
        if(pAhead->next != nullptr)
            pAhead = pAhead->next;
        else
            return nullptr;
    }
    // 第二个指针开始遍历
    pBehind = pListHead;
    while(pAhead->next != nullptr){
        pAhead = pAhead->next;
        pBehind = pBehind->next;
    }
    return pBehind;
}

int main()
{
    char *p = "hello";
    // p[0] = 'H';
    cout<<p<<endl;
    return 0;
}

原文地址:https://www.cnblogs.com/flyingrun/p/13377152.html