成绩 | 10 | 开启时间 | 2021年09月24日 星期五 19:00 |
折扣 | 0.8 | 折扣时间 | 2021年10月10日 星期日 23:55 |
允许迟交 | 否 | 关闭时间 | 2021年10月17日 星期日 23:55 |
问题描述
中缀表达式就是我们通常所书写的数学表达式,后缀表达式也称为逆波兰表达式,在编译程序对我们书写的程序中的表达式进行语法检查时,往往就可以通过逆波兰表达式进行。我们所要设计并实现的程序就是将中缀表示的算术表达式转换成后缀表示,例如,将中缀表达式
(A 一 (B*C 十 D)*E) / (F 十 G )
转换为后缀表示为:ABC*D十E*--FG十/
注意:为了简化编程实现,假定变量名均为单个字母,运算符只有+,-,*,/ 和^(指数运算,要注意运算符的结合性),可以处理圆括号 (),并假定输入的算术表达式正确。
要求:使用栈数据结构实现 ,输入的中缀表达式以#号结束
输入
整数N。表示下面有N个中缀表达式
N个由单个字母和运算符构成的表达式
输出
N个后缀表达式。
测试输入 | 期待的输出 | 时间限制 | 内存限制 | 额外进程 | |
---|---|---|---|---|---|
测试用例 1 | 以文本方式显示
| 以文本方式显示
| 1秒 | 64M | 0 |
测试用例 2 | 以文本方式显示
| 以文本方式显示
| 1秒 | 64M | 0 |
代码
还是当coding练习一下得了,具体为什么要这个算法有兴趣的自己了解一下吧。
我本次的代码参考了一下网上的“从中序转后序” 链接
学长代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
int judge(char a,char b)
{
if(b=='(')
return 1;
if (a==b&&a=='^')
return 1;
if (a==b)
return 8;
if ((a=='*'||a=='/')&& (b=='+'||b=='-'))
return 1;
if ((a=='+'||a=='-')&&(b=='*'||b=='/'))
return 8;
if (a!='^'&&b == '^')
return 8;
if (a=='^'&&b !='^')
return 1;
if ((a=='+'||a=='-')&&(b=='+'||b=='-'))
return 8;
if ((a =='*'||a=='/')&&(b=='*'||b =='/'))
return 8;
}
char Operand[1000];
char expression[1000];
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
int base=1,top=1;
int len,i,j,k,l;
memset(Operand,0,sizeof(Operand));
Operand[0]='1';
memset(expression,0,sizeof(expression));
scanf("%s",expression);
len=strlen(expression);
for(i=0;i<len-1;i++)
{
if(('a'<=expression[i]&&expression[i]<='z')||('A'<=expression[i]&&expression[i]<='Z'))
{
printf("%c",expression[i]);
continue;
}
if(expression[i]=='(')
{
Operand[top++]='(';
continue;
}
else
{
if(expression[i]==')')
{
if(expression[i-1]=='(')
{
top--;
continue;
}
else
{
while(Operand[top-1]!='(')
{
printf("%c",Operand[top-1]);
top--;
continue;
}
top--;
continue;
}
}
else
{
if(judge(expression[i],Operand[top-1])==1)
{
Operand[top++]=expression[i];
continue;
}
else
{
while((judge(expression[i],Operand[top-1])==8))
{
printf("%c",Operand[top-1]);
top--;
}
Operand[top++]=expression[i];
continue;
}
}
}
}
while(top>1)
{
printf("%c",Operand[top-1]);
top--;
}
printf("\n");
}
return 0;
}
我的代码
用auto的教程:教程
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int priority(char ch)
{
if( ch == '^' ){
return 2;
}
if (ch == '*' || ch == '/')
return 1;
if (ch == '+' || ch == '-')
return 0;
if (ch == '(')
return -1;
}
int main()
{
int N;
scanf("%d",&N);
while(N--){
string input;
cin >> input;
input.pop_back();//删掉#,用erase或者substr也行
string output;
stack<char> st;
for (auto& p : input)//auto自动确定数据类型,注意先把编译环境改成c++11
//网上都有教程
{
if (p == '+' || p == '-' || p == '*' || p == '/' || p == '('|| p == '^' )
{
if (p == '(')
st.push(p);
else
{
while ((!st.empty()) && (priority(p) <= priority(st.top())))
{
output += st.top();
st.pop();
}
st.push(p);
}
}
else if (p == ')')
{
while (st.top() != '(')
{
output += st.top();
st.pop();
}
st.pop();
}
else {
output += p;
}
}
while (!st.empty())
{
output += st.top();
st.pop();
}
cout << output << endl;
}
}