3-7 表达式转换

算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。

输入格式:

输入在一行中给出不含空格的中缀表达式,可包含+-*\以及左右括号(),表达式不超过20个字符。

输出格式:

在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。

输入样例:

2+3*(7-4)+8/4

输出样例:

2 3 7 4 - * + 8 4 / +

代码:

#include <bits/stdc++.h>
using namespace std;
int n = 0, l;

void ts(char& ch);
int cmp(char a, char b);
void p(char ch);

int main() {

	string s;
	getline(cin, s);
	n = s.size();
	stack<char> op;
	for (int i = 0; i < n; i++) {
		while (isdigit(s[i]) || s[i] == '.') {
			if (i + 1 < n && (isdigit(s[i + 1]) || s[i + 1] == '.')) {
				cout << s[i];
				l++;
			}
			else p(s[i]);
			i++;
			if (i >= n) break;
		}
		if (i >= n) break;
		if (s[i] == '(') op.push(s[i]);
		else if (s[i] == ')') {
			while (op.top() != '(') {
				p(op.top());
				op.pop();
			}
			op.pop();
			l += 2;
		}
		else {
			if (i == 0 || (i > 0 && s[i - 1] == '(')) {
				if (s[i] == '-') cout << s[i];
				l++; continue;
			}
			while (!op.empty() && cmp(s[i], op.top()) <= 0) {
				p(op.top());
				op.pop();
			}
			op.push(s[i]);
		}
	}
	while (!op.empty()) {
		p(op.top());
		op.pop();
	}
	return 0;
}


void ts(char& ch) {
	if (ch == '+' || ch == '-') ch = 1;
	else if (ch == '*' || ch == '/') ch = 2;
	else ch = 0;
}

int cmp(char a, char b) {
	ts(a); ts(b);
	if (a > b) return 1;
	if (a == b) return 0;
	if (a < b) return -1;
}
void p(char ch) {
	l++;
	if (l == n) cout << ch;
	else cout << ch << " ";
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星河边采花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值