中缀表达式转后缀C++

中缀表达式转后缀C++

转成后缀并求值,两个操作都实现了。

#include<iostream>
#include<stack>
#include<vector>
using namespace std;
string intoPost(string infix);//中缀转后缀
int calPost(string post);//后缀做运算
int calculate(int a, int b, char opt);//四则运算
bool isNumber(char s);//判断数字
bool isOpt(char s);//判断运算符
bool isLeft(char s);//判断左括号
bool isRight(char s);//判断右括号
int level(char opt);//获取运算符优先级

int main() {
	string infix;//前缀表达式
	string post;//后缀表达式
	int n = 0;//中缀表达式个数
	vector<int> result;//每个中缀表达式运算结果
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> infix;
		post = intoPost(infix);
		result.push_back(calPost(post));
		infix.erase(infix.begin(), infix.end());
	}
	for (int i = 0; i < n; i++)
		cout << result[i] << endl;
}
bool isNumber(char s) {
	if (s >= '0' && s <= '9')
		return true;
	else
		return false;
}
bool isOpt(char s) {
	if (s == '+' || s == '-' || s == '*' || s == '/')
		return true;
	else
		return false;
}
bool isLeft(char s) {
	if (s == '(')
		return true;
	else
		return false;
}
bool isRight(char s) {
	if (s == ')')
		return true;
	else
		return false;
}
int level(char opt) {
	int lev;
	if (opt == '+' || opt == '-')
		lev = 1;
	else if (opt == '*' || opt == '/')
		lev = 2;
	else
		lev = 0;
	return lev;
}
int calculate(int a, int b, char opt) {
	int sum;
	if (opt == '+')
		sum = a + b;
	else if (opt == '-')
		sum = a - b;
	else if (opt == '*')
		sum = a * b;
	else if (opt == '/')
		sum = a / b;
	else
		throw - 1;
	return sum;
}
string intoPost(string infix) {
	string post;
	stack<char> s;//符号栈
	for (int i = 0; i < infix.length(); i++) {
		if (isNumber(infix[i])) {
			post += infix[i];
			if (!isNumber(infix[i + 1]))
				post += '#';
		}
		else if (isLeft(infix[i])) {
			s.push(infix[i]);
		}
		else if (isRight(infix[i])) {
			while (!isLeft(s.top())) {
				post += s.top();
				s.pop();
			}
			s.pop();//弹出栈顶左括号
		}
		else if (isOpt(infix[i])) {
			if (s.empty())
				s.push(infix[i]);
			else {
				while (s.top()!='('&&level(s.top()) >= level(infix[i])) {
					post += s.top();
					s.pop();
					if (s.empty())
						break;
				}
				s.push(infix[i]);
			}
		}
		else
			throw - 1;
	}
	while (!s.empty()) {//把符号栈清空
		post += s.top();
		s.pop();
	}
	return post;
}
int calPost(string post) {
	stack<int> num;//储存运算中间值
	for (int i = 0; i < post.length(); i++) {
		if (isNumber(post[i])) {
			int sum = 0;
			while (isNumber(post[i])) {
				sum = sum * 10 + post[i]-'0';
				i++;
			}	
			num.push(sum);
		}
		else if (isOpt(post[i])) {
			int b = num.top();   num.pop();	
			int a = num.top();   num.pop();
			num.push(calculate(a, b, post[i]));
		}
	}
	return num.top();
}

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值