表达式求值----c++-----堆栈实现

#include <iostream>
#include <stdlib.h>
#include <stack>


using namespace std;
stack <int> num;
stack <char> ch;
///1.如果s[i]>ch.top(),那么ch.push(s[i]);
///2.如果s[i]<=ch.top(),那么ch.pop(),在和ch.top()比较,结果选择进行1 or 2
bool compare(char a,char b)//aÊÇtop
{
    if((a=='+' || a=='-') && (b=='*'||b=='/'))
         return true;
    if(b=='+'||b=='-'||a=='(')
        return false;
    return true;
}
int yunsuan()        
{
    int x2=num.top();            //注意x1与x2的顺序
    num.pop();
    int x1=num.top();
    num.pop();
    char c=ch.top();
    ch.pop();
    switch(c)
    {
    case '+':
        return x1+x2;
        break;
    case '-':
        return x1-x2;
        break;
    case '*':
        return x1*x2;
        break;
    case '/':
        return x1/x2;
        break;
    }
}
int main()
{
    string s;
    cin>>s;
    s=s+")";
    ch.push('(');
    for(int i=0; i<s.length(); i++)
        cout<<s[i]<<" ";
    cout<<endl;
    for(int i=0; i<s.length(); i++)
    {
        if(s[i]>='0' && s[i]<='9')
        {
            int a=s[i]-'0';
            for(i=i+1; i<s.length(); i++){
                if(s[i]>='0' && s[i]<='9')
                {
                    a=a*10+(s[i]-'0');
                }
                else
                {
                    i--;
                    break;
                }
            }
            num.push(a);
            cout<<a<<" ";
            continue;
        }
        if(s[i]=='(')
        {
            ch.push(s[i]);
            continue;
        }
        if(s[i] == '+' || s[i]=='-' || s[i]=='*' || s[i]=='/')
        {
            while(compare(ch.top(),s[i]))                //如果当前运算符优先级小于等于ch.top()
            {
                int x=yunsuan();
                num.push(x);
///                cout<<ch.top()<<" ";
///                ch.pop();
            }
            ch.push(s[i]);
            continue;
        }
        if(s[i]==')')
        {
            while(ch.top()!='(')
            {
                int x=yunsuan();
                num.push(x);
///                cout<<ch.top()<<" ";
///                ch.pop();
            }
            ch.pop();                    //把左括号删除
        }
    }
    cout<<num.top();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38851184/article/details/79592013