题解 | #输出单向链表中倒数第k个结点#

输出单向链表中倒数第k个结点

http://www.nowcoder.com/practice/54404a78aec1435a81150f15f899417d

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

#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;
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-02 18:35
简历上把1个月实习写成了3个月,会进行背调吗?
码农索隆:一个月有一个月的实习经历,三个月有三个月的实习经历
简历当中有水分算不算造假...
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 评论 收藏
分享
07-01 23:23
郑州大学 Java
否极泰来来来来:牛客迟早有高三的
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 12:10
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务