将一个中缀表达式,转换为后缀表达式 转换成C语言代码
时间: 2023-10-09 12:07:30 浏览: 102
很高兴为您提供帮助,以下是C语言代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
typedef enum {
lparen, rparen, plus, minus, times, divide, mod, eos, operand
} precedence;
int stack[MAX_STACK_SIZE];
char expr[MAX_STACK_SIZE];
int top = -1;
precedence get_token(char* symbol, int* n);
void push(int item);
int pop(void);
void print_token(precedence token);
int main() {
int n = 0;
char symbol;
precedence token;
printf("Enter an infix expression: ");
while ((symbol = getchar()) != '\n') {
expr[n++] = symbol;
}
expr[n] = '\0';
printf("The postfix expression is: ");
token = get_token(&symbol, &n);
while (token != eos) {
if (token == operand) {
printf("%c", symbol);
}
else if (token == rparen) {
while (stack[top] != lparen) {
print_token(pop());
}
pop();
}
else {
while (stack[top] != eos && stack[top] >= token) {
print_token(pop());
}
push(token);
}
token = get_token(&symbol, &n);
}
while ((token = pop()) != eos) {
print_token(token);
}
printf("\n");
return 0;
}
precedence get_token(char* symbol, int* n) {
*symbol = expr[(*n)++];
switch (*symbol) {
case '(': return lparen;
case ')': return rparen;
case '+': return plus;
case '-': return minus;
case '*': return times;
case '/': return divide;
case '%': return mod;
case '\0': return eos;
default: return operand;
}
}
void push(int item) {
if (top >= MAX_STACK_SIZE - 1) {
fprintf(stderr, "Stack overflow\n");
exit(EXIT_FAILURE);
}
stack[++top] = item;
}
int pop() {
if (top == -1) {
fprintf(stderr, "Stack underflow\n");
exit(EXIT_FAILURE);
}
return stack[top--];
}
void print_token(precedence token) {
switch (token) {
case lparen: printf("("); break;
case rparen: printf(")"); break;
case plus: printf("+"); break;
case minus: printf("-"); break;
case times: printf("*"); break;
case divide: printf("/"); break;
case mod: printf("%%"); break;
default: break;
}
}
```
阅读全文