Problem Description
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
Input
输入一个算术表达式,以‘#’字符作为结束标志。
Output
输出该表达式转换所得到的后缀式。
Example Input
a*b+(c-d/e)*f#
Example Output
ab*cde/-f*+
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
#define STACKINITSIZE 100
#define STACKINCREMENT 10
#define OVERFLOW -2
#define ERROR -1
#define OK 1
typedef char SElemtype;
typedef int Statu;
typedef struct node
{
SElemtype *base;
SElemtype *top;
int stacksize;
}SqStack;
int i;
SElemtype b[1110];
Statu Check(SqStack &S, SElemtype c);
Statu InitStack(SqStack &S);
Statu Push(SqStack &S, SElemtype e);
Statu Pop(SqStack &S, SElemtype &e);
int Compare(char b);
int main()
{
char a;
SqStack S;
InitStack(S);
i = 0;
while(scanf("%c", &a) && a != '#')
{
Check(S, a);
}
while(S.top != S.base)
{
Pop(S, a);
b[i++] = a;
}
printf("%s\n", b);
return 0;
}
Statu InitStack(SqStack &S)
{
S.base = (SElemtype *)malloc(STACKINITSIZE * sizeof(SElemtype));
if(!S.base)
exit(OVERFLOW);
S.top = S.base + 1;
S.stacksize = STACKINITSIZE;
return OK;
}
Statu Push(SqStack &S, SElemtype e)
{
if(S.top - S.base >= S.stacksize)
{
S.base = (SElemtype *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemtype));
if(!S.base)
exit(OVERFLOW);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
* S.top++ = e;
return OK;
}
Statu Pop(SqStack &S, SElemtype &e)
{
if(S.top == S.base)
return ERROR;
e = * -- S.top;
return OK;
}
Statu Check(SqStack &S, SElemtype c)
{
int a, d;
char k;
if(c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')')
{
if(S.top == S.base + 1)
Push(S, c);
else
{
if(c == ')')
{
while(*(S.top - 1) != '(')
{
Pop(S, k);
b[i++] = k;
}
Pop(S, k);
}
else if(c == '(')
Push(S, c);
else
{
a = Compare(c);
d = Compare(*(S.top - 1));
if(a > d)
Push(S, c);
else
{
while(S.top != S.base && d >= a)
{
Pop(S, k);
b[i++] = k;
a = Compare(c);
d = Compare(*(S.top - 1));
}
Push(S, c);
}
}
}
}
else
{
b[i++] = c;
}
return OK;
}
int Compare(char b)
{
if(b == '+' || b == '-')
return 1;
else if(b == '*' || b == '/')
return 2;
else if(b == '(')
return 0;
else
return -1;
}