中缀转后缀表达式

#include<iostream>
#include<map>
#include<stack>
#include<queue>
using namespace std;


void text01()
{
	//设置优先级!
	map<char, int>map;
	map.insert(make_pair('#', 0));
	map.insert(make_pair('+', 1));
	map.insert(make_pair('-', 1));
	map.insert(make_pair('*', 2));
	map.insert(make_pair('/', 2));
	map.insert(make_pair('(', 3));
	map.insert(make_pair(')', 3));
	//利用map容器来表示优先级


	stack<char>stack;
	queue<char>queue;
	cout << "请输入中缀表达式:" << endl;
	string str;
	cin >> str;
	stack.push('#');
	int length = str.size();
	if (str.at(0) == '+' || str.at(0) == '-' || str.at(0) == '*' || str.at(0) == '/')return ;
	if (str.at(length - 1) == '+' || str.at(length - 1) == '-' || str.at(length - 1) == '*' || str.at(length - 1) == '/')return ;

	//char temp;

	for (int i = 0; i < str.size(); i++)
	{
		if (str.at(i) == '+' || str.at(i) == '-' || str.at(i) == '*' || str.at(i) == '/' || str.at(i) == '(' || str.at(i) == ')')
		{
			while (1)
			{
				if (map[str.at(i)] > map[stack.top()])//如果优先级高的话就进栈
				{
					stack.push(str.at(i));
					if (stack.top() == ')')//如果栈顶为‘)’的话就把()之间的全部出栈,进入到queue里去;
					{
						while (1)
						{
							stack.pop();
							if (stack.top() == '(')
							{
								stack.pop();
								break;
							}
							queue.push(stack.top());

						}
					}
					break;
				}
				if (map[str.at(i)] <= map[stack.top()])//如果优先级低于栈顶或与栈顶优先级相同的话,先判断是不是‘(’,如果不是就出栈
				{
					if (stack.top() == '(')//如果栈顶为‘(’时,那么直接进栈即可
					{
						stack.push(str.at(i));
						break;
					}
					else
					{
						queue.push(stack.top());
						stack.pop();
					}
				}
			}

		}
		else//如果不是+-*/,那么进入队列里
		{
			queue.push(str.at(i));
		}
		if (i == str.size() - 1)
		{
			while (stack.top() != '#')
			{
				queue.push(stack.top());
				stack.pop();
			}//当它遍历完的时候,stack里面的全部出栈			

		}

	}

	cout << "后缀表达式为:" << endl;

	while (!queue.empty()) {
		cout << " " << queue.front();
		queue.pop();
	}
	cout << endl;
}

int main()
{
	text01();



	system("pause");
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值