自定义stack类模版,实现empty?full?push,pop,gettop,clear,display

来源:互联网 发布:淘宝淘营销活动有用吗 编辑:程序博客网 时间:2024/06/03 10:37
//stack.h定义
#include<iostream>#include<cassert>#ifndef STACK#define STACKtemplate<class T>class stack{int top;T *a;int cn;public:stack(int c);~stack();bool empty()const;bool full()const;void push(const T &item);T gettop()const;void pop();void clear();void display(const stack<T> &s1);};template<class T>//初始化栈,栈顶top=-1stack<T>::stack(int c){assert(c > 0);cn = c;a = new T[cn];//动态数组建立if (a!= 0)top = -1;elseassert(a != 0);}template<class T>//析构函数调用清除动态数组stack<T>::~stack(){delete[]a;}template<class T>//判空,top=-1则为空bool stack<T>::empty()const{return(top == -1);}template<class T>//栈满判断bool stack<T>::full()const{return(top == cn - 1);}template<class T>//压栈,首先判断是否栈满void stack<T>::push(const T &item){assert(!full());a[++top] = item;//压栈}template<class T>//取栈顶元素T stack<T>::gettop()const{assert(!empty());return a[top];}template<class T>//弹栈void stack<T>::pop(){assert(!empty());return a[top--];}template<class T>//清除栈void stack<T>::clear(){top = -1;}template<class T>//栈显示,从栈顶到栈底void stack<T>::display(const stack<T> &s1){for (int i = cn-1; i >= 0; i--)cout << s1.a[i] << " " << endl;}#endif
//main函数测试
#include<iostream>#include"stack.h"using namespace std;int main(){stack<int>s(3);cout << "stack is empty?" << s.empty() << endl;s.push(1);s.push(2);s.push(3);cout << "the stack is:" << endl;s.display(s);cout << "the top is:" << s.gettop() << endl;;s.clear();stack<char>a(3);a.push('x');a.push('u');a.push('z');a.display(a);system("pause");return 0;}

阅读全文
0 0
原创粉丝点击