// 20:05 - 20:50 #include #include #define MAX 256 int getPriority(char ch) { if (ch == '+' || ch == '-') { return 0; } else if (ch == '*' || ch == '/') { return 1; } else { return -1; } } typedef struct stack { double *arr; int top; } stack; stack *newStack() { stack *st = malloc(sizeof(stack)); st->top = 0; st->arr = malloc(sizeof(double) * MAX); return st; } void push(stack *st, double val) { // printf("Pushing: %.2lf\n", val); st->arr[st->top++] = val; } 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]); } } int main(void) { char buf[MAX]; char out[MAX]; scanf("%s", buf); toPostfix(buf, out); calculate(out); printPostfix(out); return 0; }