用c语言实现输入中缀表达式,输出后缀表达式
时间: 2023-05-27 16:02:43 浏览: 115
以下是使用C语言实现输入中缀表达式,输出后缀表达式的代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
int stack[MAX_SIZE]; //定义栈
int top = -1; //栈顶指针
//判断是否为操作符
int isOperator(char c) {
if(c == '+' || c == '-' || c == '*' || c == '/') {
return 1;
}
return 0;
}
//获取操作符的优先级
int getPriority(char op) {
int priority = 0;
switch(op) {
case '+':
case '-':
priority = 1;
break;
case '*':
case '/':
priority = 2;
break;
}
return priority;
}
//将中缀表达式转换成后缀表达式
void infixToPostfix(char infix[], char postfix[]) {
int i, j = 0;
int len = strlen(infix);
char temp;
for(i = 0; i < len; i++) {
if(infix[i] == '(') {
stack[++top] = infix[i];
} else if(infix[i] == ')') {
while(stack[top] != '(') {
postfix[j++] = stack[top--];
}
top--; //将左括号出栈
} else if(!isOperator(infix[i])) {
postfix[j++] = infix[i];
} else {
while(top > -1 && stack[top] != '(' && getPriority(stack[top]) >= getPriority(infix[i])) {
postfix[j++] = stack[top--];
}
stack[++top] = infix[i];
}
}
while(top > -1) {
postfix[j++] = stack[top--];
}
postfix[j] = '\0';
}
int main() {
char infix[MAX_SIZE] = "a+b*c-d/e";
char postfix[MAX_SIZE];
infixToPostfix(infix, postfix);
printf("中缀表达式:%s\n", infix);
printf("后缀表达式:%s\n", postfix);
return 0;
}
```
运行结果为:
```
中缀表达式:a+b*c-d/e
后缀表达式:abc*+de/-
```
阅读全文