用c语言写比较双目四则运算符优先级的算法
时间: 2023-05-20 10:02:42 浏览: 126
算符优先算法C语言实现
5星 · 资源好评率100%
可以使用栈来实现双目四则运算符的优先级,具体实现可以参考以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_SIZE 100
typedef struct {
int 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, int x) {
if (is_full(s)) {
printf("Stack is full.\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top--];
}
int 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 0;
}
}
void infix_to_postfix(char *infix, char *postfix) {
Stack s;
init(&s);
int i = 0, j = 0;
while (infix[i] != '\0') {
if (isdigit(infix[i])) {
postfix[j++] = infix[i++];
} else if (is_operator(infix[i])) {
while (!is_empty(&s) && is_operator(peek(&s)) && priority(peek(&s)) >= priority(infix[i])) {
postfix[j++] = pop(&s);
}
push(&s, infix[i++]);
} else if (infix[i] == '(') {
push(&s, infix[i++]);
} else if (infix[i] == ')') {
while (!is_empty(&s) && peek(&s) != '(') {
postfix[j++] = pop(&s);
}
if (!is_empty(&s) && peek(&s) == '(') {
pop(&s);
} else {
printf("Invalid expression.\n");
exit(1);
}
i++;
} else {
printf("Invalid character.\n");
exit(1);
}
}
while (!is_empty(&s)) {
if (peek(&s) == '(') {
printf("Invalid expression.\n");
exit(1);
}
postfix[j++] = pop(&s);
}
postfix[j] = '\0';
}
int evaluate_postfix(char *postfix) {
Stack s;
init(&s);
int i = 0;
while (postfix[i] != '\0') {
if (isdigit(postfix[i])) {
push(&s, postfix[i] - '0');
} else if (is_operator(postfix[i])) {
int b = pop(&s);
int a = pop(&s);
switch (postfix[i]) {
case '+':
push(&s, a + b);
break;
case '-':
push(&s, a - b);
break;
case '*':
push(&s, a * b);
break;
case '/':
push(&s, a / b);
break;
}
} else {
printf("Invalid character.\n");
exit(1);
}
i++;
}
return pop(&s);
}
int main() {
char infix[100], postfix[100];
printf("Enter an infix expression: ");
scanf("%s", infix);
infix_to_postfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
printf("Result: %d\n", evaluate_postfix(postfix));
return 0;
}
阅读全文