带有数组中括号的中缀转后缀表达式的C例子
时间: 2023-09-19 18:05:50 浏览: 94
以下是带有数组中括号的中缀表达式转后缀表达式的 C 语言实现示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_SIZE 100
typedef struct {
int top;
char data[STACK_SIZE];
} Stack;
void stack_init(Stack *s) {
s->top = -1;
}
int stack_is_empty(Stack *s) {
return s->top == -1;
}
void stack_push(Stack *s, char c) {
if (s->top == STACK_SIZE - 1) {
printf("Error: stack overflow\n");
exit(1);
}
s->top++;
s->data[s->top] = c;
}
char stack_pop(Stack *s) {
if (stack_is_empty(s)) {
printf("Error: stack underflow\n");
exit(1);
}
char c = s->data[s->top];
s->top--;
return c;
}
char stack_peek(Stack *s) {
if (stack_is_empty(s)) {
printf("Error: stack underflow\n");
exit(1);
}
return s->data[s->top];
}
int is_operator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '%';
}
int is_left_bracket(char c) {
return c == '(' || c == '[';
}
int is_right_bracket(char c) {
return c == ')' || c == ']';
}
int is_array_bracket(char c) {
return c == '[' || c == ']';
}
int get_priority(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
default:
return 0;
}
}
void infix_to_postfix(char *infix, char *postfix) {
Stack stack;
stack_init(&stack);
int i = 0, j = 0;
while (infix[i] != '\0') {
char c = infix[i];
if (isdigit(c) || isalpha(c)) {
postfix[j++] = c;
} else if (is_operator(c)) {
while (!stack_is_empty(&stack) && is_operator(stack_peek(&stack)) && get_priority(c) <= get_priority(stack_peek(&stack))) {
postfix[j++] = stack_pop(&stack);
}
stack_push(&stack, c);
} else if (is_left_bracket(c)) {
stack_push(&stack, c);
} else if (is_right_bracket(c)) {
while (!stack_is_empty(&stack) && !is_left_bracket(stack_peek(&stack))) {
postfix[j++] = stack_pop(&stack);
}
if (!stack_is_empty(&stack) && is_left_bracket(stack_peek(&stack))) {
stack_pop(&stack);
} else {
printf("Error: mismatched brackets\n");
exit(1);
}
if (is_array_bracket(c)) {
postfix[j++] = c;
}
} else {
printf("Error: invalid character '%c'\n", c);
exit(1);
}
i++;
}
while (!stack_is_empty(&stack)) {
char c = stack_pop(&stack);
if (is_left_bracket(c) || is_right_bracket(c)) {
printf("Error: mismatched brackets\n");
exit(1);
}
postfix[j++] = c;
}
postfix[j] = '\0';
}
int main() {
char infix[] = "((a+b)*c)/(d-e)[0]";
char postfix[strlen(infix) + 1];
infix_to_postfix(infix, postfix);
printf("%s\n", postfix);
return 0;
}
```
运行结果为:
```
ab+c*d-e[0]/
```
阅读全文