一种数据项按序排列的数据结构
特点由于只能在一端(称为栈顶(top))对数据项进行插入和删除, 因此堆栈中元素先进后出
适用条件内存分配 取放盘子 电梯人员出入等符合堆栈特点的操作
常用函数stack例题q; //以int型为例 int x; q.push(x); //将x压入栈顶 q.top(); //返回栈顶的元素 q.pop(); //删除栈顶的元素 q.size(); //返回栈中元素的个数 q.empty(); //检查栈是否为空,若为空返回true,否则返回false q.emplace(); //将自定义数据类型压入栈顶使用emplace.
操作栈 51Nod - 3199
#include#define int long long #define rep(i, a, b) for(int i=a;ib;--i) using namespace std; const int N = 100005; inline int read(){ int s=0,w=1; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();} while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar(); return s*w; } void put(int x) { if(x<0) putchar('-'),x=-x; if(x>=10) put(x/10); putchar(x%10^48); } signed main(){ stack st; int n=read(); while(n--){ int m=read(); if(m==1){ int x=read(); st.push(x); } else{ if(st.empty()){ printf("empty"); } else{ put(st.top()); puts(""); st.pop(); } } } return 0; }
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈



