表达式转换
分数 5
作者 DS课程组
单位 浙江大学
算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+、-、*、/以及左右括号(),表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
c++详解:
#include<iostream>
#include<cstdlib>
#include<cctype>
using namespace std;
#define MAXSIZE 25 //初始栈中容纳的最大容量
#define INCREMENT 20 // 动态分配需再次添加的容量
typedef struct stack{
char *elem; //数组地址,为数组分配足够大的空间储存元素
char *top;
int stacksize; // 数组中可储存的元素个数
}seqstack, *stacklink;
void initstack(stacklink s){
s->elem = (char*)malloc(4*MAXSIZE);
if(s->elem == NULL) cout << "when initstack Empty stack" << endl;
s->top = s->elem;
s->stacksize = MAXSIZE;
}
void push(stacklink s, char x){
if(s->top - s->elem >= s->stacksize){
s->elem = (char*)realloc(s->elem, 4*(s->stacksize + INCREMENT));
if(s->elem == NULL) cout << "when push Empty stack" << endl;
s->top = s->elem + s->stacksize;
s->stacksize = s->stacksize + INCREMENT;
}
*s->top++ = x;
}
int stacklength(stacklink s){
return s->top - s->elem;
}
int pop(stacklink s, char *x){
if(stacklength(s) == 0) return 0;
else {
*x = *--s->top;
return 1;
}
}
void Transform(stacklink s, char str[], char output[]){
char temp;
initstack(s);
int i = 0, j = 0; // j is the index for output
while(str[i] != '\0'){
while(isdigit(str[i])){
output[j++] = str[i++];
if(!isdigit(str[i])) output[j++] = ' ';
}
if(str[i] == '+' || str[i] == '-'){
if(stacklength(s) == 0) push(s,str[i]);
else{
do{
pop(s,&temp);
if(temp == '(') push(s,temp);
else output[j++] = temp, output[j++] = ' ';
}while(temp != '(' && stacklength(s));
push(s,str[i]);
}
}
else if(str[i] == '*' || str[i] == '/' || str[i] =='(') push(s,str[i]);
else if(str[i] == ')'){
pop(s, &temp);
while(temp != '(') {
output[j++] = temp, output[j++] = ' ';
pop(s, &temp);
}
}
// else cout << " errro input" << endl;
i++;
}
while(stacklength(s) > 1){
pop(s, &temp);
output[j++] = temp, output[j++] = ' ';
}
if(stacklength(s)){
pop(s, &temp);
output[j++] = temp;
}
if (output[j-1] == ' ') output[j-1] = '\0';
else output[j] = '\0';
}
int main(){
char str[MAXSIZE],put[100];
fgets(str, MAXSIZE, stdin);
seqstack s;
Transform(&s,str,put);
cout << put;
}