/* mbinary ######################################################################### # File : stack.cc # Author: mbinary # Mail: zhuheqin1@gmail.com # Blog: https://mbinary.coding.me # Github: https://github.com/mbinary # Created Time: 2018-04-26 10:33 # Description: ######################################################################### */ #include #include #include #define SZ 50 using namespace std; template class stack { int capacity; type *bottom,*top; public: stack(int n = SZ); stack( stack &); stack(int,type); stack(vector &); type pop(); int cp(); void push(type); bool empty(); type getTop(); }; template stack::stack(int n):capacity(n) { bottom = new type[capacity+1]; top = bottom; } template stack::stack(int n,type x):capacity(n*2) { bottom = new type[capacity+1]; top = bottom; for(int i = 0;i stack::stack(vector &vc):capacity (vc.size()*2) { bottom = new type[capacity+1]; top = bottom; for(int i = 0;i!=vc.size();++i){ push(vc[i]); } } template stack::stack(stack &s):capacity(s.capacity) { bottom = new type[capacity+1]; top = bottom; for(type *p= s.bottom;p!=s.top;)*(++top) = *(++p); } template int stack::cp() { return capacity; } template bool stack::empty() { return bottom == top; } template type stack::getTop() { return *top; } template type stack::pop() { if(bottom == top){ printf("the stack is empty now\n"); return 0; }else{ return *(top--); } } template void stack::push(type x) { if(capacity == top-bottom){ bottom = (type *)realloc(bottom,sizeof(type)*(2*capacity+1)); top = bottom+capacity; } *(++top) = x; } int main() { stack sc(5,'z'),scc(sc); printf("stack copy\n"); while(!scc.empty()){ printf("%c\n",scc.pop()); } vector vc(50,2.3); stack sd(vc); sd.push(3.4); printf("gettop%lf\n",sd.getTop()); printf("vec copy\n"); while(!sd.empty()){ printf("%lf\n",sd.pop()); } printf("empty %d\ncapacity%d",sd.empty(),sd.cp()); return 0; }