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