请写一个中缀表达式转后缀表达式的C++代码,要求满足四则运算和取余运算
时间: 2023-03-31 07:04:36 浏览: 151
C++实现中缀表达式转后缀表达式
5星 · 资源好评率100%
好的,以下是中缀表达式转后缀表达式的 C 代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
typedef struct {
char data[MAX_STACK_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isFull(Stack *s) {
return s->top == MAX_STACK_SIZE - 1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
void push(Stack *s, char c) {
if (isFull(s)) {
printf("Stack overflow\n");
exit(1);
}
s->data[++s->top] = c;
}
char pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top--];
}
char peek(Stack *s) {
if (isEmpty(s)) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top];
}
int isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '%';
}
int precedence(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
default:
return ;
}
}
void infixToPostfix(char *infix, char *postfix) {
Stack s;
initStack(&s);
int i = , j = ;
while (infix[i] != '\') {
if (isdigit(infix[i])) {
postfix[j++] = infix[i++];
while (isdigit(infix[i])) {
postfix[j++] = infix[i++];
}
postfix[j++] = ' ';
} else if (isOperator(infix[i])) {
while (!isEmpty(&s) && isOperator(peek(&s)) && precedence(peek(&s)) >= precedence(infix[i])) {
postfix[j++] = pop(&s);
postfix[j++] = ' ';
}
push(&s, infix[i++]);
} else if (infix[i] == '(') {
push(&s, infix[i++]);
} else if (infix[i] == ')') {
while (!isEmpty(&s) && peek(&s) != '(') {
postfix[j++] = pop(&s);
postfix[j++] = ' ';
}
if (!isEmpty(&s) && peek(&s) == '(') {
pop(&s);
} else {
printf("Mismatched parentheses\n");
exit(1);
}
i++;
} else if (isspace(infix[i])) {
i++;
} else {
printf("Invalid character: %c\n", infix[i]);
exit(1);
}
}
while (!isEmpty(&s)) {
if (peek(&s) == '(') {
printf("Mismatched parentheses\n");
exit(1);
}
postfix[j++] = pop(&s);
postfix[j++] = ' ';
}
postfix[j] = '\';
}
int main() {
char infix[100], postfix[100];
printf("Enter an infix expression: ");
fgets(infix, sizeof(infix), stdin);
infixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
return ;
}
```
希望能够帮到你!
阅读全文