堆栈练习

来源:互联网 发布:java软件工程师查工资 编辑:程序博客网 时间:2024/05/16 11:24

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



0 0
原创粉丝点击