中缀表达式转后缀并求值

这是个中缀表达式的求解,过程是先进行转换成后缀,然后我用的数组保存数,然后求解,我写的目前只限于单位数的中缀表达式…

#include<iostream>
#include<stack>
#include<string>
using namespace std;

int check(char buff) {
    if (buff == '+' || buff == '-')return 1;
    if (buff == '*' || buff == '/')return 2;
    if (buff == '(')return 3;
    if (buff == ')')return 4;
    return 0;
}
bool check_(char buff) {
    if (buff == '+' || buff == '-' || buff == '*' || buff == '/' || buff == '(' || buff == ')')
        return true;
    return false;
}

int main(void) {
    string buff;
    cin >> buff;
    stack<char>st;
    stack<char>num;
    for (int i = 0; i<buff.length(); i++) {
        if (check_(buff[i])) {//判定是否是运算符;
            if (st.empty())
                st.push(buff[i]);//栈为空就先将运算符压入;
            else if (check(buff[i])>check(st.top())) {//当前运算符优先于栈顶运算符;
                if (check(buff[i]) == 4) {
                    while (st.top() != '(') {
                        num.push(st.top());
                        st.pop();
                    }
                    if (st.top() == '(') {
                        st.pop();
                    }
                }
                else {
                    st.push(buff[i]);
                }
            }
            else {//当前运算符低于栈顶运算符;
                if (st.top() != '(') {
                    num.push(st.top());
                    st.pop();
                    st.push(buff[i]);
                }
                else
                    st.push(buff[i]);

            }
        }
        else num.push(buff[i]);
    }
    while (!st.empty()) {//将剩余运算符压入num栈;
        num.push(st.top());
        st.pop();
    }
    stack<char >te;//矫正顺序,num栈是逆序
    while (!num.empty()) {
        cout << num.top();
        te.push(num.top());
        num.pop();
    }
    cout<<endl;
    int i=0,arr[100];
    while(!te.empty()){//用数组存取数字,然后求解;
        if(!check_(te.top())){
           arr[i++]=te.top()-'0';
           te.pop();
        }
        else{
            if (te.top() == '+'){
                arr[i-2]+=arr[i-1];
                i--;
                te.pop();
            }
            else if (te.top() == '-'){
                arr[i-2]-=arr[i-1];
                i--;
                te.pop();
            }
            else if (te.top()== '*'){
                arr[i-2]*=arr[i-1];
                i--;
                te.pop();
            }
            else if (te.top() == '/'){
                arr[i-2]/=arr[i-1];
                i--;
                te.pop();
            }
        }
    }
    cout<<arr[0];
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值