stack和queue的初级应用

来源:互联网 发布:全面战争战锤优化 编辑:程序博客网 时间:2024/06/09 17:58

栈stack的初级应用:

stack:操作 比较和分配堆栈 empty() 堆栈为空则返回真 pop() 移除栈顶元素 push() 在栈顶增加元素 size() 返回栈中元素数目 top() 返回栈顶元素 //数值运算,十进制转八进制#include<cstdio>#include<iostream>#include<stack>#include<cstring>using namespace std;int main(){    int n;    cin>>n;    int m;    stack<int>s;    while(n/8)    {        m=n%8;        n=n/8;        s.push(m);    }    m=n%8;    s.push(m);    while(!s.empty())    {        cout<<s.top();        s.pop();    }    cout<<endl;    return 0;}

sdut2133
利用二目运算符,每次遇到运算符,就从栈中取出两个数,进行运算后再将其写入栈中,千万不要忘了取出之后,将此值从栈中移除。

//后缀表达式的计算#include<iostream>#include<cstdio>#include<cstring>#include<stack>using namespace std;int main(){    char s[1002]={0};    stack<int>s1;    while(~scanf("%s",s))    {        int i,j;        for(i=0;i<strlen(s);++i)        {            if(s[i]=='#')                break;            if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/')            {                int n=s1.top();                s1.pop();                int m=s1.top();                s1.pop();                int k;                switch(s[i])                {                    case '+':k=n+m;break;                    case '-':k=m-n;break;                    case '*':k=n*m;break;                    case '/':k=m/n;break;                }                s1.push(k);                continue;            }            s1.push(s[i]-'0');        }        cout<<s1.top()<<endl;    }    return 0;}
原创粉丝点击