3-06. 表达式转换

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

输入格式说明:

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

输出格式说明:

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

样例输入与输出:

序号 输入 输出
1
2+3*(7-4)+8/4
2 3 7 4 - * + 8 4 / +
2
((2+3)*4-(8+2))/5
2 3 + 4 * 8 2 + - 5 /
3
1314+25.5*12
1314 25.5 12 * +
4
-2*(+3)
-2 3 *
5
123
123

中缀表达式到后缀表达的转换思路(网上一堆资料):
1. 若是数字则直接放到输出;
2. 若是操作符‘+’/‘-’/’*‘/’、’, 则放入一个运算符堆栈,放入之前判断当前运算符优先级是否大于栈顶运算符,是则直接压入,不是则将栈顶元素出栈放入输出中,指到当前运算符优先级大于栈顶元素或栈为空后,讲当前运算符入栈;这里要注意,‘+’、-、符号若是前面不是运算因子,则只是作为正负数的标识,并不是运算符;
3. 若是‘(’,则直接入栈,入栈后‘(’的优先级降至最低;
4. 若是‘)’, 将栈顶元素出栈放入输出中,指到遇到栈顶元素为‘(’为止;
5. 输入全部读完后,若是栈中还有元素,全部出栈病放入输出中。

源代码:
#include<iostream>
#include<stack>
#include<string>
#include<iterator>
#include<cctype>
using namespace std;

int main()
{
	string in,out;
	char curr, fore=-1, next;
	string::iterator iter;
	stack<char> stk;
	
	cin >> in;
	for(iter=in.begin(); iter!=in.end(); iter++)
	{
		curr = *iter;
		/*if it is a digit, add to the output immediately*/
		if((curr>='0'&& curr<='9') || curr=='.')
		{
			out.push_back(curr);
			if((iter+1)==in.end() || (!isdigit(*(iter+1))&& *(iter+1)!='.'))	//pay attention that '.' is a part of number
				out.push_back(' ');
		}
		else if(curr == '+' || curr == '-')
		{
			if(fore == '(' || fore == -1)	//if '+'/'-' add befor a number ,and the fore is not a compute factor, it indicate a number is negative or not
				if(curr == '+')
					continue;
				else
					out.push_back(curr);
			else
			{
				if(stk.empty())
					stk.push(curr);
				else if(stk.top() != '(')
				{
					while(!stk.empty() && stk.top() != '(')
					{
						out.push_back(stk.top());
						out.push_back(' ');
						stk.pop();
					}
					stk.push(curr);
				}
				else
					stk.push(curr);
			}
		}
		else if(curr == '*' ||curr == '/')
		{
			if(stk.empty() || stk.top() != '*' ||stk.top() != '/')
			{
				stk.push(curr);
			}
			else
			{
				while(!stk.empty() && (stk.top() == '*' || stk.top() =='/'))
				{
					out.push_back(stk.top());
					out.push_back(' ');
					stk.pop();
				}
				stk.push(curr);
			}
		}
		else if(curr == '(')
		{
			stk.push(curr);
		}
		else if(curr == ')')
		{
			while(stk.top() != '(')
			{
				out.push_back(stk.top());
				out.push_back(' ');
				stk.pop();
			}
			stk.pop();
		}
		fore = curr;
	}
	
	while(!stk.empty())
	{
		out.push_back(stk.top());
		out.push_back(' ');
		stk.pop();
	}
	
	for(iter=out.begin(); iter!=(out.end()-1); iter++)
		cout<< *iter;
	cout<<endl;
	
	return 0;
}




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值