波兰式中缀变后缀(蒟蒻学c++打卡)

发布时间 2023-04-12 22:12:51作者: 喜欢网络冲浪の小蒜头

//stack 运算式中序变后序波兰式(前中后序)

 

原题:

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

输入格式原题:

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

输出格式:

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

输入样例:

2+3*(7-4)+8/4

输出样例:

2 3 7 4 - * + 8 4 / +

思路(看完答案知道的)://详细题解:https://b23.tv/YDatPY1

1、数字直接输出

2、栈空直接入栈

3、遍历时遇到“+-”退栈,退到栈中遇到“+-”停止,将栈中“+-”输出,然后自己入栈,“(”停止,将自己入栈

4、遍历时遇到“)”也需要退栈,遇到“(”停止,将左括号弹出

代码:

#include<iostream>
#include<cstring>
#include<stack>
using namespace std;

//符号优先级
int priority(char c)
{
switch (c)
{
case '+': return 1;
case '-': return 1;
case '*': return 2;
case '/': return 2;
}
return 0;
}
void infixtosuffix(char str[], int length)
{
string result;
stack<char> stack;
for (int i = 0; i < length; i++)
{
//暂存当前字母
char c = str[i];
//如果是数字直接输出
if (isdigit(c))
{
result += c;
continue;
}
//如果栈空 c是( c优先级大于栈顶优先级 直接入栈;
if (stack.empty() || c == '(' || priority(c) > priority(stack.top()))
{
stack.push(c);
continue;
}
//如果 c是( 循环到(出栈
if (c == ')')
{
while (!stack.empty() && stack.top() != '(')
{
result += stack.top();
stack.pop();
}
stack.pop();//弹(
continue;
}
//c优先级<= 栈顶优先级 循环出栈并加入到结果中直到栈顶字符优先级< c优先级且栈非空
while (!stack.empty() && priority(c) <= priority(stack.top()))
{
result += stack.top();
stack.pop();
}
//c入栈
stack.push(c);
}
// 循环结束,若栈非空,循环出栈并加入到结果中,知道栈空
while(!stack.empty())
{
result+=stack.top();
stack.pop();
}
cout << result << endl;
}
int main()
{
char s[100];cin>>s;
infixtosuffix(s , strlen(s));
return 0;
}