题解 | #【模板】栈# 头插法单链表,用了构造和析构
【模板】栈
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")
查看21道真题和解析