7-4 表达式转换 (25 分)
算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+
、-
、*
、\
以及左右括号()
,表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
这个题,真他妈的坑!!!!
坑点:
1.有个位以上的数 123 输出 123
2.有小数 12.3 输出 12.3
3.数字前边有符号 2*(+3) 输出 -2 3 * -1--1 输出 -1 -1 - -1-+2 输出 -1 2 +
而且这个题还他妈的一个数据错其余全错? fuck
代码:
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <string>
#include <cstdio>
#include <vector>
#include <iomanip>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long
#define lowbit(x) (x&(-x))
#define mem(a,b) memset(a,b,sizeof(a))
#define FRER() freopen("in.txt","r",stdin);
#define FREW() freopen("out.txt","w",stdout);
using namespace std;
const int maxn = 50000 + 7;
struct Stacak{
char *base;
char *top;
void Init(int m){
base = (char *)malloc(m*sizeof(char));
top = base;
}
void Pop(){
--top;
}
void Push(char e){
*top++ = e;
}
bool Empty(){
if(top==base) return true;
return false;
}
char Top(){
return *(top-1);
}
};
bool isNum(char c){
if(c=='.'||('0'<=c&&c<='9')) return true;
return false;
}
bool flag;
void pr(){//前导空格
if(flag) printf(" ");
}
int main(){
Stacak S;
S.Init(1000);
char s[1000];
int p[1000];
scanf("%s",s);
p['*'] = p['/'] = 2;
p['+'] = p['-'] = 1;
while(!S.Empty()){
printf("%c\n",S.Top());
S.Pop();
}
for(int i=0;s[i];){
if(s[i]=='+'||s[i]=='-'){
if(i==0){// -1+3 这种情况
if(s[i]=='-'){
printf("-");
flag = true;
}
i++;
while(isNum(s[i])){//处理多位
printf("%c",s[i]);
flag = true;
i++;
}
}else if(s[i-1]=='('){//1+(-2) 这种情况
pr();
if(s[i]=='-'){
printf("-");
flag = true;
}
i++;
while(isNum(s[i])){
printf("%c",s[i]);
flag = true;
i++;
}
}else if(s[i-1]=='+'||s[i-1]=='-'||s[i-1]=='*'||s[i-1]=='/'){//-1--1这种情况
pr();
if(s[i]=='-'){
printf("-");
flag = true;
}
i++;
while(isNum(s[i])){
printf("%c",s[i]);
flag = true;
i++;
}
}
else{
while(!S.Empty()&&p[S.Top()]>=p[s[i]]&&S.Top()!='('){
pr();
printf("%c",S.Top());
S.Pop();
flag = true;
}
S.Push(s[i]);
i++;
}
}
else if(s[i]=='*'||s[i]=='/'){
while(!S.Empty()&&p[S.Top()]>=p[s[i]]&&S.Top()!='('){
pr();
printf("%c",S.Top());
S.Pop();
flag = true;
}
S.Push(s[i]);
i++;
}
else if('0'<=s[i]&&s[i]<='9'){
pr();
while(isNum(s[i])){
printf("%c",s[i]);
i++;
flag = true;
}
}
else if(s[i]=='('){
S.Push(s[i]);
i++;
}else if(s[i]==')'){
while(S.Top()!='('){
pr();
printf("%c",S.Top());
S.Pop();
flag = true;
}
S.Pop();
i++;
}
}
while(!S.Empty()){
pr();
printf("%c",S.Top());
S.Pop();
flag = true;
}
printf("\n");
}