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

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

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

#include <bits/stdc++.h>
using namespace std;

struct ListNode
{
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next_) : val(x), next(next_) {}
};

 

int main() {
    int a, b, c;
   stack<ListNode*> m;

    while(cin >> a )
    {
        struct ListNode* ret=  new ListNode();
        ListNode* cur= ret;
        while (a--) {
            cin >> b;
            struct ListNode *temp = new ListNode(b);
            cur->next = temp;
            m.push(cur->next);
            cur = cur->next;
        }
        cin >> c;

        while(!m.empty())
        {
            ListNode* p = m.top();
            m.pop();
            c--;
            if(c==0)
            {
                cout << p->val<<'\n';
                break;
            }
        }

        
    }
    

}
// 64 位输出请用 printf("%lld")

全部评论
哇呀呀呀
点赞 回复 分享
发布于 2023-05-05 20:50 广东

相关推荐

评论
点赞
收藏
分享

创作者周榜

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