多语言展示
当前在线:842今日阅读:167今日分享:16

怎么手写stack

stack是STL中的一个模板,可是我们不但要会用,还要会写(只写了int类型的stack)
工具/原料

c++编译器

确定隐藏部分

隐藏部分很少,就两个。int len; vectora;

函数
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; }//指针交换

总体

class 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; vectora;}

推荐信息