求助用栈改中缀为后缀表达式RE
  • 板块学术版
  • 楼主histcat
  • 当前回复0
  • 已保存回复0
  • 发布时间2022/1/27 21:18
  • 上次更新2023/10/28 10:42:20
查看原帖
求助用栈改中缀为后缀表达式RE
361592
histcat楼主2022/1/27 21:18
#include<iostream>
#include<stack>
using namespace std;

int check(char a)//判断是否是数字或字母
{
	if(a >= '0' && a <= '9')
	{
		return 1;
	}
	else if(a >= 'a' && a <= 'z')
	{
		return 1;
	}
	else if(a >= 'A' && a <= 'Z')
	{
		return 1;
	}
	return 0;
}

int yxj(char a)//优先级+判断是否是符号
{
	if(a == '*' || a == '/')
		return 2;
	if(a == '+' || a == '-')
		return 1;
	return -1;
}


int main()
{
	stack<char> temp;
	string front = "";
	cin >> front;
	for(long long i = 0;front[i];i++)
	{
		if(check(front[i]) == 1)
		{
			cout << front[i];
		}
		else if(front[i] == '(')
		{
			temp.emplace(front[i]);
		}
		else if(yxj(front[i]) == 2 || yxj(front[i]) == 1)
		{
			while(yxj(temp.top()) >= yxj(front[i]) && temp.size())
			{
				cout << temp.top();
				temp.pop();
			}
			temp.emplace(front[i]);
		}
		else if(front[i] == ')')
		{
			while(temp.top() != '(' && temp.size())
			{
				cout << temp.top();
				temp.pop();
			}
			if(temp.size()) temp.pop();
		}
	}
	while(temp.size())//处理剩下的符号
	{
		cout << temp.top();
		temp.pop();
	}
	return 0;
}
2022/1/27 21:18
加载中...