第4关:STL模板之栈stack实例:计算机求解后缀表达式

后缀表达式 #include <iostream> #include <stack> #include <string> using namespace std; // 判断是否为数字 bool is_digit(char c) { return c >= '0' && c <= '9'; } // 判断是否为操作符 bool is_operator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } // 获取操作符的优先级 int get_priority(char op) { if (op == '+' || op == '-') { return 1; } else if (op == '*' || op == '/') { return 2; } else { return 0; } } // 将中缀表达式转换为后缀表达式 string infix_to_postfix(string infix) { string postfix; // 后缀表达式 stack<char> op_stack; // 操作符 // 遍历中缀表达式 for (int i = 0; i < infix.size(); i++) { char c = infix[i]; if (is_digit(c)) { // 如果是数字,直接加入后缀表达式 postfix += c; } else if (c == '(') { // 如果是左括号,入 op_stack.push(c); } else if (c == ')') { // 如果是右括号,弹出中操作符直到遇到左括号 while (!op_stack.empty() && op_stack.top() != '(') { postfix += op_stack.top(); op_stack.pop(); } if (!op_stack.empty()) { op_stack.pop(); // 弹出左括号 } } else if (is_operator(c)) { // 如果是操作符 // 弹出中优先级高于等于当前操作符的操作符 while (!op_stack.empty() && get_priority(op_stack.top()) >= get_priority(c)) { postfix += op_stack.top(); op_stack.pop(); } op_stack.push(c); // 当前操作符入 } } // 弹出中剩余的操作符 while (!op_stack.empty()) { postfix += op_stack.top(); op_stack.pop(); } return postfix; } int main() { string infix = "3+(4*5/(6-7))"; string postfix = infix_to_postfix(infix); cout << postfix << endl; // 345*67-/+ return 0; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值