Answer to Question #289476 in C for engay

Question #289476

Write program to convert a postfix expression to infix expression with parentheses on each operation .


1
Expert's answer
2022-01-22T02:42:02-0500
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct Stack_ {
    char* data[1024];
    int top;
} Stack;

void init(Stack* s) {
    s->top = 0;
}

void push(Stack* s, char* p) {
    s->data[(s->top)++] = p;
}

char* pop(Stack* s) {
    return s->data[--(s->top)];
}

int empty(Stack* s) {
    return s->top == 0;
}

char* postfix2infix(const char* src) {
    char* buf;
    Stack s;
    char* p, * x, * y, * res;
    char op[4] = {' ', '*', ' ', '\0'};
    int len;

    init(&s);
    buf = (char *) malloc(strlen(src)+1);
    strcpy(buf, src);
    p = strtok(buf, " ");

    while (p != NULL) {
        if ( *p == '+' || *p == '-' || *p == '*' || *p == '/') {
            x = pop(&s);
            y = pop(&s);
            len = 5 + strlen(x) + strlen(y) + 1;
            res = (char *) malloc(len);
            strcpy(res, "(");
            strcat(res, y);
            op[1] = *p;
            strcat(res, op);
            strcat(res, x);
            strcat(res, ")");
            push(&s, res);
            free(x);
            free(y);
        }
        else {
            len = strlen(p) + 1;
            res = (char *) malloc(len);
            strcpy(res, p);
            push(&s, res);
        }
        p = strtok(NULL, " ");
    }
    free(buf);
    res = pop(&s);
    return res;
}

int main() {
    char* str1 = "a b c + +";
    char* str2 = "a b * c +";
    char* res;

    res = postfix2infix(str1);
    printf("Input: %s\n", str1);
    printf("Output: %s\n", res);
    free(res);

    res = postfix2infix(str2);
    printf("\nInput: %s\n", str2);
    printf("Output: %s\n", res);
    free(res);

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS