代码
template<class T>
class Stack
{
private:
class Node
{
public:
T x;
Node* next;
Node(){}
Node(T t,Node* next){
this->x = t;
this->next = next;
}
Node(Node& node){
this->x = node.x;
this->next = node.next;
}
};
Node* top;
int num;
public:
Stack(){
top = new Node(0,nullptr);
num = 0;
}
~Stack(){
while(top->next!=nullptr){
Node* temp = top->next;
top->next = top->next->next;
delete temp;
}
delete top;
num = 0;
}
void push(T t){
Node* oldfirst = top->next;
Node* newfirst = new Node(t,nullptr);
newfirst->next = oldfirst;
top->next = newfirst;
num++;
}
T pop(){
if(top->next!=nullptr){
Node* temp = top->next;
top->next = top->next->next;
T val = temp->x;
delete temp;
num--;
return val;
}
}
int getlength(){
return num;
}
};