您的位置:首页 > 其它

堆栈练习

2015-12-20 20:38 483 查看

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: