c++中的栈、stack的初步应用

来源:互联网 发布:godaddy虚拟主机 java 编辑:程序博客网 时间:2024/06/14 08:33

1、定义

stack</*变量类型*/>/*变量名*/;
如:

stack<int>a;
就定义了一个叫a的栈

记得一定要加头文件

#include<stack>

2、相关函数及运用

注:以下所有函数表达在已定义栈a的情况下

①  a.push()//把一个元素推入栈a中②  a.pop()//把最上面的元素踢出栈a③  a.top()//访问栈最顶端④  a.size()//返回元素个数⑤  a.empty()//判断栈空(栈空返回true)
举个栗子例子吧

就拿洛谷P1739作为水题代表吧#洛谷P1739#
许多人看到这题,想:如此水,设备sb才会用栈呢~

。。。呵呵好吧,我就是那个设备【手动滑稽】

先上水打法

#include<bits/stdc++.h>using namespace std;void read(int &x){//字符串写读入优化    x=0;char c=getchar();    while(c<'0' || c>'9')c=getchar();    while(c>='0' && c<='9'){        x=x*10+c-'0';        c=getchar();    }}void write(int x){//输出优化        int y=10,len=1;        while(y<=x)  {y*=10;len++;}        while(len--){y/=10;putchar(x/y+48);x%=y;}    } char ch;int i,flag;int main(){    ios::sync_with_stdio(0);   do     {            cin>>ch;        if(ch=='(')        {            ++i;flag=1;//没错,flag=1说明第一个括号是左括号        }            else if(ch==')')        {            if(flag==0)    break;//如果第一个括号是右括号,那么就可以退出循环了(肯定不匹配啊~)            --i;        }    }    while(ch!='@');    if(i==0&&flag==1)    cout<<"YES";    else    cout<<"NO";    return 0; }

再上传说中的栈

#include<bits/stdc++.h>#include<stack>//虽然写了万能头文件,但还要再写一遍加粗表强调using namespace std;void read(int &x){//字符串写读入优化    x=0;char c=getchar();    while(c<'0' || c>'9')c=getchar();    while(c>='0' && c<='9'){        x=x*10+c-'0';        c=getchar();    }}void write(int x){//输出优化        int y=10,len=1;        while(y<=x)  {y*=10;len++;}        while(len--){y/=10;putchar(x/y+48);x%=y;}    } stack<char>st;int main(){    ios::sync_with_stdio(false);    char a;cin>>a;//读入    while(a!='@')    {        if(a=='(')st.push('(');//左括号就扔到栈里        else if(a==')'&&st.empty()){cout<<"NO";return 0;}//如果遇到右括号时栈已经空了就输出NO结束(也避免第一个是“)”的情况)        else if(a==')')st.pop();//遇到右括号扔一个左括号        cin>>a;//读下一个    }    if(st.empty()){cout<<"YES";return 0;}//如果表达式结束栈空了就可以    cout<<"NO";//否则不行}

好像没什么了233……

1 0
原创粉丝点击