1、Vector实现
#ifndef STACK
#define STACK
#include <vector>
template<class T, int capacity = 30>
class Stack{
public:
Stack(){
pool.reserve(capacity);
}
//清空
void clear(){
pool.clear();
}
//判断堆栈是否为空
bool isEmpty() const{
return pool.empty();
}
//获取顶部元素,但是不修改
T& topE1(){
return pool.back();
}
//弹出栈顶元素
T pop(){
T el = pool.back();
pool.pop_back();
return el;
}
//将el元素放入栈顶
void push(const T& el){
pool.push_back(el);
}
private:
std::vector<T> pool;
};
#endif
2、链表实现
#ifndef LL_STACK
#define LL_STACK
#include <list>
using namespace std;
template <class T>
class LLStack{
public:
LLStack(){
}
void clear(){
lst.clear();
}
bool isEmpty() const{
return lst.empty();
}
T& topEl(){
return lst.back();
}
T top(){
T el = lst.back();
lst.pop_back();
return el;
}
void push(const T& el){
lst.push_back(el);
}
private:
list<T> lst;
};
#endif