BUPT-homework/semester3/pset1/7-2-Infix-to-Postfix-Conversion.c

123 lines
2.4 KiB
C
Raw Normal View History

2022-11-20 21:22:03 +08:00
// 20:05 - 20:50
2022-10-14 18:47:09 +08:00
#include <stdio.h>
2022-11-20 21:22:03 +08:00
#include <stdlib.h>
#define MAX 256
int getPriority(char ch) {
if (ch == '+' || ch == '-') {
return 0;
} else if (ch == '*' || ch == '/') {
return 1;
} else {
return -1;
}
}
2022-10-14 18:47:09 +08:00
typedef struct stack {
2022-11-20 21:22:03 +08:00
double *arr;
2022-10-14 18:47:09 +08:00
int top;
} stack;
2022-11-20 21:22:03 +08:00
stack *newStack() {
stack *st = malloc(sizeof(stack));
st->top = 0;
st->arr = malloc(sizeof(double) * MAX);
return st;
2022-10-14 18:47:09 +08:00
}
2022-11-20 21:22:03 +08:00
void push(stack *st, double val) {
// printf("Pushing: %.2lf\n", val);
st->arr[st->top++] = val;
2022-10-14 18:47:09 +08:00
}
2022-11-20 21:22:03 +08:00
double top(stack *st) { return st->arr[st->top - 1]; }
void pop(stack *st) { st->top--; }
int isEmpty(stack *st) { return (st->top == 0); }
void toPostfix(char *buf, char *out) {
int count = 0;
stack *st = newStack();
for (int i = 0; buf[i] != '\0'; i++) {
if (buf[i] >= '0' && buf[i] <= '9') {
// is digit, push to out array
out[count++] = buf[i];
} else {
if (buf[i] == '(') {
// left paren, don't pop elements in stack.
push(st, buf[i]);
} else if (buf[i] == ')') {
// push everything after the (
while (top(st) != '(') {
out[count++] = top(st);
pop(st);
}
pop(st);
} else {
// the equal sign is important
while (!isEmpty(st) && getPriority(top(st)) >= getPriority(buf[i])) {
out[count++] = top(st);
pop(st);
}
push(st, buf[i]);
}
}
}
while (!isEmpty(st)) {
out[count++] = top(st);
pop(st);
}
out[count] = '\0';
}
void calculate(char *postfix) {
double l, r;
stack *st = newStack();
for (int i = 0; postfix[i] != '\0'; i++) {
if (postfix[i] >= '0' && postfix[i] <= '9') {
// remember convert from char to int
push(st, postfix[i] - '0');
} else {
r = top(st);
pop(st);
l = top(st);
pop(st);
if (postfix[i] == '+') {
push(st, l + r);
} else if (postfix[i] == '-') {
push(st, l - r);
} else if (postfix[i] == '*') {
push(st, l * r);
} else if (postfix[i] == '/') {
push(st, l / r);
} else {
printf("ERROR: %c is not recognized\n", postfix[i]);
}
}
}
printf("%.2lf\n", top(st));
}
void printPostfix(char *postfix) {
for (int i = 0; postfix[i] != '\0'; i++) {
printf("%c ", postfix[i]);
}
2022-10-14 18:47:09 +08:00
}
int main(void) {
2022-11-20 21:22:03 +08:00
char buf[MAX];
char out[MAX];
scanf("%s", buf);
toPostfix(buf, out);
calculate(out);
printPostfix(out);
return 0;
2022-10-14 18:47:09 +08:00
}