中缀表达式转换为后缀表达式
最近在复习考研,C语言+数据结构,在此记录实验代码,仅供参考
#include <stdio.h>
#include <string.h>
int yxj(char p,char q) //判断运算符优先级
{
if((p == '+' || p == '-') && (q == '*' || q == '/'))
{
return 0;
}
else {
if(p == q)
{
return 0;
}
else {
return 1;
}
}
}
int main()
{
char str[15] = "(a+b*c)/d-e",stack[100];
int top = -1;
char *p = str;
while(*p != '\0')
{
if(*p >= 'a' && *p <= 'z')
{
printf("%c",*p);
}
else {
if(*p == '(' || *p == '[' || *p == '{')
{
stack[++top] = *p;
}
else {
if(*p == ')')
{
while(stack[top] != '(' && stack[top] != '[' && stack[top] != '{')
{
printf("%c",stack[top--]);
stack[top + 1] = ' ';
}
if(stack[top] != '(')
{
printf("括号不匹配!");
return 0;
}
else {
top--;
stack[top + 1] = ' ';
}
}
if(yxj(*p,stack[top]))
{
stack[++top] = *p;
}
else {
printf("%c",stack[top--]);
stack[top] = *p;
}
}
}
p++;
}
while(stack[top] == '+' || stack[top] == '-' || stack[top] == '*' || stack[top] == '/')
{
printf("%c",stack[top--]);
}
if(top != -1)
{
printf("括号不匹配!");
}
return 0;
}