中缀表达式转化为后缀表达式

8 篇文章 0 订阅

题目:

中缀表达式转化为后缀表达式

例如:

1+(2-3)*4+7/5         ----->       123-4*+75/+

思路分析:

1、首先要清楚中缀表达式转化我后缀表达式的规则:

1)遇到数字输出,否则进栈。

2)遇到有右括号匹配栈里的左括号,输出栈里的内容

3)遇到比自己比栈里的运算符优先级高,入栈

4)遇到比自己比栈里的运算符优先级低,将栈里的运算符出栈

代码

#include <iostream>
#include <stack>
#include <string>

using namespace std;

int Compare(char n_ope);
string middle_to_final(string s1);

int main(int argc,char* argv[])
{
	string test = "1+(2-3)*4+7/5";
	string result = middle_to_final(test);
	cout << result << endl;
	return 0;
}


int Compare(char n_ope)
{
	if (n_ope == '+' || n_ope == '-') return 1;
	if (n_ope == '*' || n_ope == '/') return 2;
	if (n_ope == '(') return 0;
	return -1;
}

/*
转换规则:
1.遇到数字输出,否则进栈。
2.遇到有右括号匹配栈里的左括号,输出栈里的内容
3.遇到比自己比栈里的运算符优先级高,入栈
4.遇到比自己比栈里的运算符优先级低,将栈里的运算符出栈
*/

//只支持1-9的正整数,不支持2位数和负数
string middle_to_final(string s1)
{
	string result;
	stack<char> st1;
	string::iterator it;
	for ( it= s1.begin(); it!= s1.end(); it++)
	{
		if ((*it) > '0' && (*it) < '9')
		{
			result.push_back(*it);
			continue;
		}//finish

		if ((*it) == '(')
		{
			st1.push(*it);
			continue;
		}//finish
		
		
		if ((*it) == ')')
		{
			while((st1.top())!='(')
			{
				result.push_back(st1.top());
				st1.pop();
			}
			st1.pop();
			continue;
		}
		else
		{
			//一定要判断st1是否为空,否则段错误
			while (!st1.empty() && Compare(st1.top()) >= Compare(*it))
			{
				result.push_back(st1.top());
				st1.pop();
			}
			st1.push(*it);
		}
	}
	
	while (!st1.empty())
	{
		result.push_back(st1.top());
		st1.pop();
	}
	

	return result;

}

待优化:

1、不支持负数和大于等于2位数的计算,做到这点可以考虑用字符数组替代string

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值