问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
题目算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+、-、*、\以及左右括号(),表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入是 2+3*(7-4)+8/4
输出是 2 3 7 4 - * + 8 4 / +
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<iomanip>
using namespace std;
typedef struct SNode *List;
struct SNode
{
char Data;
List Next;
};
int ss(char a,char b)
{
if(a=='+'||a=='-')
{
if(b=='+'||b=='-'||b=='#'||b==')')
{
return 0;
}
else
{
return 1;
}
}
else if(a=='*'||a=='/')
{
if(b=='+'||b=='-'||b=='*'||b=='/'||b=='#'||b==')')
{
return 0;
}
else
{
return 1;
}
}
else if(a=='(')
{
return 1;
}
else if(a=='#')
{
if(b!='#')
{
return 1;
}else
{
return 0;
}
}else
{
return 10;
}
}
int main()
{
char s[10000];
char c;
int cnt=1;
cin.get(c);
s[0]=c;
while(c!='\n')
{
cin.get(c);
s[cnt++]=c;
}
List L2=(List)malloc(sizeof(struct SNode));
List p=(List)malloc(sizeof(struct SNode));
p->Data='#';
L2->Next=p;
s[cnt-1]='#';
int n=0;
while(n<cnt&&L2->Next)
{
if(s[n]>='0'&&s[n]<='9')
{
if(n==cnt-1)
{
cout<<s[n];
}else
{
cout<<s[n]<<" ";
}
}
else
{
if(L2->Next->Data=='#')
{
List w=(List)malloc(sizeof(struct SNode));
w->Data=s[n];
w->Next=L2->Next;
L2->Next=w;
//cout<<L2->Next->Data<<endl;;
}
else
{
char m=L2->Next->Data;
int x=ss(m,s[n]);
//cout<<m<<" "<<s[n]<<" "<<x<<endl;
if(x==1)
{
List d=(List)malloc(sizeof(struct SNode));
d->Data=s[n];
d->Next=L2->Next;
L2->Next=d;
}
else if(x==0)
{
while(x==0&&L2->Next)
{
if(L2->Next->Data!='('&&L2->Next->Data!=')'&&L2->Next->Data!='#')
{
if(n==cnt-1)
{
cout<<L2->Next->Data;
}else
{
cout<<L2->Next->Data<<" ";
}
}
L2=L2->Next;
char l=L2->Next->Data;
if(l=='('&&s[n]==')'&&L2->Next)
{
L2=L2->Next;
break;
}
x=ss(l,s[n]);
if(x==1)
{
List v=(List)malloc(sizeof(struct SNode));
v->Data=s[n];
v->Next=L2->Next;
L2->Next=v;
}
}
}
}
}
n++;
}
}