怎么手写stack
stack是STL中的一个模板,可是我们不但要会用,还要会写(只写了int类型的stack)
工具/原料
c++编译器
确定隐藏部分
1、隐藏部分很少,就两个。int len; vector<int>a;
函数
1、void push(int x){a.push_back(x); len++; }//添加
2、void pop(){ len--; a.pop_back(); }//弹出
3、int top(){ return a[len-1]; }//顶端元素
4、int size(){ return len; }//长度
5、bool empty(){ return len==0; }//判空
6、void swap(stac x,stac y拘七呷憎){ stac *x1,*x2; x1=&y; x2=&x; stac *x3; x3=x1; 艘早祓胂 x1=x2; x2=x3; }//指针交换
总体
1、clas衡痕贤伎s stac{ public: void push(int x){ a.push_back(x); len++; }艘早祓胂 void pop(){ len--; a.pop_back(); } int top(){ return a[len-1]; } int size(){ return len; } bool empty(){ return len==0; } void swap(stac x,stac y){ stac *x1,*x2; x1=&y; x2=&x; stac *x3; x3=x1; x1=x2; x2=x3; } private: int len; vector<int>a;}