#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 100
typedef struct{
char *base;
char *top;
int stacksize;
}sqStack;
void initStack(sqStack *s)//初始化
{
s->base = (char *)malloc(STACK_INIT_SIZE*sizeof(char));
if(!s->base) exit(0);
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
}
void 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) exit(0);
s->top = s->base + s->stacksize;
s->stacksize +=STACKINCREMENT;
}
*(s->top) = e;
s->top++;
}
void Pop(sqStack *s)//出栈
{
if(s->top==s->base) return;
s->top--;
}
int main()
{
sqStack s;
char ch;
initStack(&s);
while(~scanf("%c",&ch)&&(ch!='#'))
{
if(ch>='a'&&ch<='z')//如果是操作数直接输出
printf("%c",ch);
else if(ch=='(')//如果是‘(’则压入栈中
Push(&s,ch);
else if(ch==')')//如果是‘)’,依次出栈并输出,直到取出和它匹配的‘(’为止,‘(’出栈
{
while(*(s.top-1)!='(')
{
printf("%c",*(s.top-1));
Pop(&s);
}
Pop(&s);
}
/*若是操作数,如果栈空或者该操作符的优先级大于栈顶操作符则将其放入栈中;
如果该操作符的优先级小于等于栈顶操作符,则弹出栈中的操作符并输出,
直到该操作符的优先级大于栈顶操作符或栈空,然后将该操作符入栈。
*/
else if(ch=='+'||ch=='-')
{
if((s.top!=s.base)&&(*(s.top-1)!='('))
{
printf("%c",*(s.top-1));
Pop(&s);
}
Push(&s,ch);
}
else if(ch=='*'||ch=='/')
{
if((s.top==s.base)||(*(s.top-1)!='*')||(*(s.top-1)!='/'))
Push(&s,ch);
else
{
printf("%c",*(s.top-1));
Pop(&s);
Push(&s,ch);
}
}
}
while(s.top!=s.base)//输出栈
{
printf("%c",*(s.top-1));
Pop(&s);
}
return 0;
}