栈模板的实现

来源:互联网 发布:淘宝汽车配件的台湾件 编辑:程序博客网 时间:2024/05/16 16:00

1.用向量容器实现栈模板

//用向量实现的栈模板#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& topEL()   {   return pool.back();//返回一个栈顶元素    }   T pop()             //出栈操作    {   T el=pool.back();   pool.pop_back();   return el;   }   void push(const T&el)//进栈操作    {   pool.push_back(el);   }   private:vector<T>pool;     //定义向量容器对象 };#endif 


2.用线性链表实现栈模板

//用链表实现的栈模板 #ifndef LL_STACK#define LL_STACK#include<list>template<class T>class LLStack{public:void clear(){likst.clear();      //清除栈中元素 }bool isEmpty() const{return likst.empty(); //判断栈是否为空 }T& topEL(){return likst.back();//返回栈顶元素 }T pop()                 //出栈操作 {T el=likst.back();likst.pop_back();return el;}void push(const T&el)   //进栈操作 {likst.push_back(el);}private:list<T>likst;           //定义链表对象 };#endif



0 0
原创粉丝点击