Write program to convert a postfix expression to infix expression with parentheses on each operation .
#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;
}
Comments
Leave a comment