算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+、-、*、\以及左右括号(),表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
卡了挺长时间的一道题,自己第一次的代码太乱了,而且有一个测试点还过不了,索性重新写了一遍,结果就ac了。。。。。。。。太难顶了
不过话说回来是数组模拟太难了,还是stl不香了,非要作死写指针。。。。
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<set>
#include<cmath>
#include<vector>
#include<cstdlib>
#include<cctype>
using namespace std;
struct node
{
char data;
int level;
node *pre,*next;
};
struct Stack
{
node *head,*last;
Stack()
{
head=new node();
last=new node();
head->next=nullptr;
last=head;
}
char do_top()
{
return last->data;
}
int top_level()
{
return last->level;
}
void do_pop()
{
node *p=last->pre;
free(last);
last=p;
last->next=nullptr;
}
bool isempty()
{
if(head==last)
return true;
return false;
}
void do_push(char x, int a)
{
node *newNode = new node();
newNode->data = x;
newNode->level = a;
newNode->next = NULL;
newNode->pre = last;
last->next = newNode;
last = newNode;
}
};
bool space=false;//判断是否输出空格
void print()
{
if(space)
cout<<" ";
space=true;
}
int main()
{
string s;
cin>>s;
Stack in;
bool flag=false;//判断符号是运算符还是正负号
for(int i=0; i<s.size(); i++)
{
if(i<s.size()-1&&((s[i]=='-'||s[i]=='+')&&!flag))
{
char p=s[i];
i++;
double ans=0;
int den=0;
int k=0;
while(i<s.size()&&(s[i]>='0'&&s[i]<='9')||s[i]=='.')
{
if(s[i]=='.')
{
den=10;
i++;
continue;
}
if(den==0)
ans=ans*10+s[i]-'0';
else
{
ans+=(double)(s[i]-'0')/den*1.0;
den*=10;
}
i++;
k=1;
}
if(k)
{
i--;
if(p=='-')
ans=-ans;
print();
cout<<ans;
flag=true;
}
}
else if(s[i]<'0'||s[i]>'9')
{
int a;
if(s[i]=='+'||s[i]=='-')
a=0;
else if(s[i]=='*'||s[i]=='/')
a=1;
else
a=3;
if(in.isempty()&&s[i]!=')')
in.do_push(s[i],a);
else if(s[i]==')')
{
while(!in.isempty()&&in.do_top()!='(')
{
print();
cout<<in.do_top();
in.do_pop();
}
if(!in.isempty())
in.do_pop();
}
else
{
if(s[i]=='(')
{
in.do_push(s[i],a);
flag=false;
}
else
{
if(in.top_level()<a)
in.do_push(s[i],a);
else
{
while(!in.isempty()&&in.top_level()>=a&&in.do_top()!='(')
{
print();
cout<<in.do_top();
in.do_pop();
}
in.do_push(s[i],a);
}
}
}
}
else
{
double ans=0;
int dem=0;
int k=0;
while(i<s.size()&&((s[i]>='0'&&s[i]<='9')||s[i]=='.'))
{
k=1;
if(s[i]=='.')
{
dem=10;
i++;
continue;
}
if(dem==0)
ans=ans*10+s[i]-'0';
else
{
ans+=(double)(s[i]-'0')/dem*1.0;
dem*=10;
}
i++;
}
if(k)
{
flag=true;
print();
cout<<ans;
i--;
}
}
}
while(!in.isempty())
{
if(in.do_top()=='(')
{
in.do_pop();
continue;
}
print();
cout<<in.do_top();
in.do_pop();
}
}