0

在 C++ 中,我尝试使用堆栈将这些中缀表达式()+-*/转换为后缀,但输出不会打印出所有输入。程序运行后,括号未显示在输出中。也没有错误。

此图显示了编译后的输出:

图片

编码:

#include <iostream>
#include <堆栈>
#include <strings.h>
    
使用命名空间标准;

int operatorPrecedence(char 运算符);
无效中缀后缀(字符串 exp);
    
主函数()
{
    字符串表达式;
    cout << "输入中缀表达式:"; 辛 >> exp;
    中缀后缀(exp);
    返回0;
}
    
int operatorPrecedence(字符运算符){
    //检查运算符的优先级
    if (operators == '/') 返回 2;
    否则 if (operators == '*') return 2;
    否则 if (operators == '+') return 1;
    否则 if (operators == '-') return 1;
    否则返回-1;
}

无效中缀后缀(字符串表达式){
    堆栈<char> s;
    s.push('N');//栈中元素表示栈尾
    int len = exp.length();
    
    string ns;//结果的最终字符串
    for(int i = 0; i < len; i++){
    
        //将操作数存入显示字符串
        if ((exp[i] >= 'A' && exp[i] <= 'Z') || (exp[i] >= 'a' && exp[i] <='z') || (exp [i] >= '0' && exp[i] <= '9'))
            ns += exp[i];
    
        //检查大括号/括号
        否则 if (exp[i] == '(')
            s.push(exp[i]);
        否则 if (exp[i] == ')'){
            而 (s.top() != 'N' && s.top() != '('){
                字符 c = s.top();
                s.pop();
                ns += c;
            }
            //如果为空则弹出括号
            if (s.top() == '('){
                字符 c = s.top();
                s.pop();
            }
        }
        别的{
            //检查扫描的算子是否小于入栈的算子
            while (s.top() != 'N' && operatorPrecedence(exp[i]) <= operatorPrecedence(s.top())){
                字符 c = s.top();
                s.pop();
                ns += c;
            }
            s.push(exp[i]);
        }
    }

    //弹出堆栈中存储的所有其他内容
    而 (s.top() != 'N'){
        字符 c = s.top();
        s.pop();
        ns += c;
    }

    cout << "后缀表达式:" << ns << endl;
}
4

0 回答 0