题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=257
后缀表达式:依次读入字符,
1>当为数字时,直接进入表达式;
2>为左括号时,入栈;
2>为右括号时,弹栈进入表达式,直到遇见第一个右括号。并将读入的右括号和栈中的左括号丢弃;
3>为除括号外的其他运算符时,判断优先级:
若当前读入的运算符优先级小于或等于栈顶的运算符时,弹栈进入表达式,直到栈顶的运算符优先级小于当前读入的运算符。再将当前读入的运算符入栈(如果栈为空,则直接入栈)
4>将栈中剩余的字符弹出到表达式.
#include <stdio.h>
#include <string.h>
char stack[1005];
char suffix[1005];
char buffer[1005];
int s_top=0;
int main()
{
void s_push(char x);
char s_pop(void);
bool priority(char top_op,char InfixExp_op);
bool isoperator(char c);
int t;
int i;
int j;
scanf("%d",&t);
while(t--)
{
memset(suffix,'\0',sizeof(suffix));
s_top=0;
scanf("%s",buffer);
for (i=0,j=0;i<strlen(buffer);i++)
{
if(buffer[i]>='0'&&buffer[i]<='9') //为数字,直接进入后缀表达式
suffix[j++]=buffer[i];
if(buffer[i]=='(') //左括号,入栈
s_push('(');
if(buffer[i]==')') //右括号,弹栈到左括号
{
while(stack[s_top]!='(')
suffix[j++]=s_pop();
s_pop(); //丢弃'('
}
if(isoperator(buffer[i]) )
{
if(s_top==0)
s_push(buffer[i]);
else
{
while( priority(stack[s_top],buffer[i]) &&s_top!=0 ) //运算符,判断优先级
suffix[j++]=s_pop();
s_push(buffer[i]);
}
}
}
while(s_top)
suffix[j++]=s_pop();
printf("%s\n",suffix);
}
}
void s_push(char x)
{
s_top++;
stack[s_top]=x;
}
char s_pop(void)
{
if(s_top)
{
return stack[s_top--];
}
}
bool priority(char top_op,char InfixExp_op)
{
if(top_op=='(')
return false;
if(top_op=='*'||top_op=='/') //当前处理的运算符小于或等于栈顶的运算符时
return true;
if(InfixExp_op=='+'||InfixExp_op=='-')
return true;
return false;
}
bool isoperator(char c) //判断是不是运算符
{
if(c=='+'||c=='-'||c=='*'||c=='/')
return true;
return false;
}