题解 | #【模板】栈# 头插法单链表,用了构造和析构

【模板】栈

https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf

#include <iostream>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
using namespace std;

struct linkList
{
    int value;
    linkList* next;
};

//头插法单链表,第一个节点是头结点,统计栈内元素数量
class Stack
{
private:
linkList* stack;

public:
    Stack()
    {
        this->stack = new linkList;
        this->stack->next = nullptr;
        this->stack->value = 0;
    }

    void Push(const int& val)
    {
        linkList* ptr = new linkList;
        ptr->value = val;
        ptr->next = this->stack->next;
        this->stack->next = ptr;
        this->stack->value++;
    }

    string Pop()
    {
        if(getstackElemNum())
        {
            string result;
            linkList* ptr = this->stack->next;
            this->stack->next = ptr->next;
            result = to_string(ptr->value);
            delete ptr;
            this->stack->value--;
            return result;
        }
        else
            return "error";
    }

    string Top()
    {
        if(getstackElemNum())
            return to_string(this->stack->next->value);
        else
            return "error";
    }

    int getstackElemNum()
    {
        return this->stack->value;
    }

    ~Stack()
    {
        while(getstackElemNum())
        {
            linkList* ptr = this->stack->next;
            this->stack->next = ptr->next;
            delete ptr;
            this->stack->value--;
        }

        delete this->stack;
    }

};

int main() 
{
    string command;
    Stack st;
    while(getline(cin, command))
    {
        stringstream ss;
        string tmp;
        int value;
        if(command.find("push") != string::npos)
        {
            ss<<command;
            ss>>tmp>>value;
            st.Push(value);
        }
        else if(command.find("pop") != string::npos)
        {
            cout<<st.Pop()<<endl;
        }
        else if(command.find("top") != string::npos)
        {
            cout<<st.Top()<<endl;
        }
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

政委qqq:这道题在算法竞赛里唯一考的就是高精度,但是只能难住C++这类语言,Python直接a+b秒天秒地
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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