使用C语言写一段中缀表达式转后缀表达式的代码
时间: 2023-03-27 18:03:54 浏览: 85
以下是使用 C 语言写的中缀表达式转后缀表达式的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_full(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, char c) {
if (is_full(s)) {
printf("Stack is full.\n");
exit(1);
}
s->data[++s->top] = c;
}
char pop(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top--];
}
char peek(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top];
}
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int priority(char c) {
if (c == '*' || c == '/') {
return 2;
} else if (c == '+' || c == '-') {
return 1;
} else {
return ;
}
}
void infix_to_postfix(char *infix, char *postfix) {
Stack s;
init(&s);
int i = , j = ;
while (infix[i] != '\') {
if (infix[i] == '(') {
push(&s, infix[i]);
} else if (infix[i] == ')') {
while (peek(&s) != '(') {
postfix[j++] = pop(&s);
}
pop(&s);
} else if (is_operator(infix[i])) {
while (!is_empty(&s) && peek(&s) != '(' && priority(peek(&s)) >= priority(infix[i])) {
postfix[j++] = pop(&s);
}
push(&s, infix[i]);
} else {
postfix[j++] = infix[i];
}
i++;
}
while (!is_empty(&s)) {
postfix[j++] = pop(&s);
}
postfix[j] = '\';
}
int main() {
char infix[MAX_SIZE], postfix[MAX_SIZE];
printf("Enter infix expression: ");
scanf("%s", infix);
infix_to_postfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
return ;
}
```
这段代码可以将中缀表达式转换为后缀表达式。
阅读全文