中缀表达式转后缀表达式

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

输入格式说明:

输入在一行中给出不含空格的中缀表达式,可包含+、-、*、\以及左右括号(),表达式不超过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
考虑到输出是以空格间隔的字符串,使用一个vector<string>存储结果。

维护一个栈。遍历输入字符串s的字符,若s[i]是数字,检测连续的数字字符串,存入结果数组。

若s[i]是字符,判断s[i]与栈顶字符的优先级:

若s[i]是左括号,直接入栈;

若s[i]是右括号,依次将栈顶的加减乘除号弹出存入结果数组,最后弹出左括号;

若s[i]为乘除号,将栈顶的乘除号弹出并存入结果数组,最后s[i]入栈;

若s[i]是加减号,依次将栈顶的加减乘除号弹出并存入结果数组,最后s[i]入栈。

需要注意加号与正号的区分,负号与减号的区分。

/*2015.8.8cyq*/
#include <iostream>
#include <stack>
#include <string>
#include <vector>
#include <fstream>
using namespace std;

//ifstream fin("case5.txt");
//#define cin fin

int main(){
	string s;
	cin>>s;
	int n=s.size();
	stack<char> stk;
	vector<string> result;
	int i=0;
	string tmp;
	bool flag=true;
	while(i!=n){
		if(s[i]=='('){//左括号,入栈
			stk.push(s[i]);
			i++;
		}else if(s[i]==')'){//右括号,处理到左括号位置,存入结果数组
			while(stk.top()!='('){
				tmp=stk.top();
				result.push_back(tmp);
				stk.pop();
			}
			stk.pop();
			i++;
		}else if(s[i]=='*'||s[i]=='/'){
			if(stk.empty()||stk.top()=='('||stk.top()=='+'||stk.top()=='-'){
				stk.push(s[i]);
				i++;
			}else{
				tmp=stk.top();
				result.push_back(tmp);
				stk.pop();
				stk.push(s[i]);
				i++;
			}
		}else if(s[i]=='+'){
			if(i==0||s[i-1]=='(')//正号,而不是加号,直接忽略
				i++;
			else{
				while(!stk.empty()&&stk.top()!='('){
					tmp=stk.top();
					result.push_back(tmp);
					stk.pop();
				}
				stk.push(s[i]);
				i++;
			}
		}else if(s[i]=='-'){
			if(i==0||s[i-1]=='('){//负号,而不是减号
				flag=false;
				i++;
			}else{
				while(!stk.empty()&&stk.top()!='('){
					tmp=stk.top();
					result.push_back(tmp);
					stk.pop();
				}
				stk.push(s[i]);
				i++;
			}
		}else{//数字,直接存入结果数组
			tmp.clear();
			if(!flag){
				flag=true;
				tmp+="-";
			}
			while(i<n&&(s[i]>='0'&&s[i]<='9'||s[i]=='.')){
				tmp+=s[i];
				i++;
			}
			result.push_back(tmp);
		}
	}

	while(!stk.empty()){
		tmp=stk.top();
		stk.pop();
		result.push_back(tmp);
	}
	int len=result.size();
	if(len>0)
		cout<<result[0];
	for(int i=1;i<len;i++){
		cout<<" "<<result[i];
	}
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值