无脑使用标准库,好孩子不要学哦

#include<iostream>
#include<forward_list>

int main(int argc, char const *argv[])
{
    int node = 0,key = 0, node_num = 0;
    std::forward_list<int> lst;
    while (std::cin >> node_num)
    {
        auto iter = lst.before_begin();
        while (node_num--)
        {
            std::cin >> node;
            lst.emplace_after(iter, node);
        }
        std::cin >> key;

        lst.reverse();

        //双指针来取倒数第K个节点
        auto mit = lst.begin();
        for (auto it=lst.begin(); it != lst.end(); it++)
        {
            if (key-- <= 0)
            {
                mit++;
            }
        }
        std::cout << *mit <<std::endl;
        lst.clear();
    }
    
    return 0;
}


根据题意的解法,好孩子可以学。但只能学一点点

#include<iostream>

typedef struct ListNode
{
    int m_nKey;
    ListNode* m_pNext;
}LST;

void Print(LST *list, int key);

int main(int argc, char const *argv[])
{
    int node = 0,key = 0, node_num = 0;
    while (std::cin >> node_num)
    {
        LST *headList = nullptr;//头结点指针
        LST *last = nullptr;//游标指针,采用尾插法,所以一直指向最后一个节点

        while (node_num--)
        {
            std::cin >> node;
            auto a = new LST;
            a->m_nKey = node;
            
            if (!last)
            {
                last = a;
                headList = a;
            }
            else
            {
                last->m_pNext = a;
                last = a;
            }
        }
        std::cin >> key;

        Print(headList, key);
    }

    return 0;
}

void Print(LST *list, int key)
{
    LST *last = list;
    while (list)
    {
        if (key-- <= 0)
        {
            last = last->m_pNext;
        }
        
        list = list->m_pNext;
    }
    std::cout << last->m_nKey <<std::endl;
}