MIT-Curricular/DS/C/Lab/Week6/PrefixToInfix.c

74 lines
1.3 KiB
C

#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
char stack[MAX_SIZE][MAX_SIZE];
int top = -1;
void push(const char *item)
{
if (top >= MAX_SIZE - 1)
{
printf("Stack Overflow\n");
return;
}
strcpy(stack[++top], item);
}
char *pop()
{
if (top < 0)
{
printf("Stack Underflow\n");
return NULL;
}
return stack[top--];
}
int isOperator(char c)
{
return (c == '+' || c == '-' || c == '*' || c == '/');
}
int isAlphanumeric(char c)
{
return ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));
}
void prefixToInfix(char *prefix)
{
int len = strlen(prefix);
char temp[MAX_SIZE];
for (int i = len - 1; i >= 0; i--)
{
if (isAlphanumeric(prefix[i]))
{
temp[0] = prefix[i];
temp[1] = '\0';
push(temp);
}
else if (isOperator(prefix[i]))
{
char op1[MAX_SIZE], op2[MAX_SIZE], result[MAX_SIZE];
strcpy(op1, pop());
strcpy(op2, pop());
sprintf(result, "(%s%c%s)", op1, prefix[i], op2);
push(result);
}
}
printf("Infix expression: %s\n", stack[top]);
}
int main()
{
char prefix[MAX_SIZE];
printf("Enter prefix expression: ");
gets(prefix);
prefixToInfix(prefix);
return 0;
}