STL 栈:中缀表达式值(expr)

输入一个中缀表达式(由 0-9 组成的运算数、加+减—乘*除/四种运算符、左右小括号组成。注意“—”也可作为负数的标志,表达式以“@”作为结束符),判断表达式是否合法,如果不合法,请输出“NO”;否则请把表达式转换成后缀形式,再求出后缀表达式的值并输出。

注意:必须用栈操作,不能直接输出表达式的值。

输入

输入一行为一个以@结束的字符串。

输出

如果表达式不合法,请输出“NO”,要求大写。

如果表达式合法,请输出计算结果。

样例

输入

1+2*8-9@

输出

8

提示

注意其中的加减乘除符号!!

[参考代码]

#include<bits/stdc++.h>
using namespace std;
char str[10000];
int n;
stack<int>s1;//数字
stack<char>s2;//运算符
void calc() {
	int y=s1.top();
	s1.pop();
	int x=s1.top();
	s1.pop();
	char z=s2.top();
	s2.pop();
	if(z=='+')
		s1.push(x+y);
	else if(z=='-')
		s1.push(x-y);
	else if(z=='*')
		s1.push(x*y);
	else
		s1.push(x/y);
}
i
后缀表达式 #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、付费专栏及课程。

余额充值