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

74 lines
1.3 KiB
C
Raw Normal View History

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