# 数据结构实验之栈与队列二：一般算术表达式转换成后缀式

Problem Description

Input

Output

Sample Input

a*b+(c-d/e)*f#

Sample Output

ab*cde/-f*+

Hint

#include <stdio.h>
#include <stdlib.h>

struct stack
{
char ch[100];
int len;
};
void Init(struct stack *s)
{
s->len=0;
}
void push(struct stack *s,char ch)
{
s->ch[s->len++]=ch;
}
int IsE(struct stack *s)
{
if(s->len==0)return 0;
else return 1;
}
void pop(struct stack *s)
{
if(IsE)s->len--;
}
int top(struct stack *s)
{
if(IsE)return s->ch[s->len-1];
}
int main()
{
char s[100];
int i;
struct stack st;
Init(&st);
scanf("%s",s);
for(i=0; s[i]!='#'; i++)
{
if(s[i]<='z'&&s[i]>='a')printf("%c",s[i]);///字母直接输出
else if(s[i]=='(')///左括号入栈
{
push(&st,s[i]);
}
else if(s[i]==')')///右括号
{
while(IsE(&st)&&top(&st)!='(')///左括号后面的都输出
{
printf("%c",top(&st));
pop(&st);
}
if(top(&st)=='(')pop(&st);
}
else if(s[i]=='+'||s[i]=='-')///栈空或者是顶部为左括号，入栈；否则输出栈顶元素并且入栈
{
if(IsE(&st)==0||top(&st)=='(')
{
push(&st,s[i]);
}
else
{
printf("%c",top(&st));
pop(&st);
push(&st,s[i]);
}
}
else if(s[i]=='*'||s[i]=='/')///栈非空或者栈顶元素优先级比乘除低，入栈；若为乘除则出栈后在入栈
{
if(!IsE(&st)&&(top(&st)=='/'||top(&st)=='*'))
{
printf("%c",top(&st));
pop(&st);
}
push(&st,s[i]);
}
}
while(IsE(&st)==1)///把栈内元素输出
{
printf("%c",top(&st));
pop(&st);
}
printf("\n");
return 0;
}