2024-09-03 00:26:38 +05:30
|
|
|
#include <stdio.h>
|
|
|
|
#include <string.h>
|
|
|
|
|
|
|
|
#define MAX_SIZE 100
|
|
|
|
|
|
|
|
char stack[MAX_SIZE];
|
|
|
|
int top = -1;
|
|
|
|
|
2024-09-03 11:27:09 +05:30
|
|
|
void push(char item)
|
|
|
|
{
|
|
|
|
if (top >= MAX_SIZE - 1)
|
|
|
|
{
|
2024-09-03 00:26:38 +05:30
|
|
|
printf("Stack Overflow\n");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
stack[++top] = item;
|
|
|
|
}
|
|
|
|
|
2024-09-03 11:27:09 +05:30
|
|
|
char pop()
|
|
|
|
{
|
|
|
|
if (top < 0)
|
|
|
|
{
|
2024-09-03 00:26:38 +05:30
|
|
|
printf("Stack Underflow\n");
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
return stack[top--];
|
|
|
|
}
|
|
|
|
|
2024-09-03 11:27:09 +05:30
|
|
|
int precedence(char symbol)
|
|
|
|
{
|
|
|
|
switch (symbol)
|
|
|
|
{
|
|
|
|
case '^':
|
|
|
|
return 3;
|
|
|
|
case '*':
|
|
|
|
case '/':
|
|
|
|
return 2;
|
|
|
|
case '+':
|
|
|
|
case '-':
|
|
|
|
return 1;
|
|
|
|
default:
|
|
|
|
return 0;
|
2024-09-03 00:26:38 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-03 11:27:09 +05:30
|
|
|
void infixToPostfix(char infix[], char postfix[])
|
|
|
|
{
|
2024-09-03 00:26:38 +05:30
|
|
|
int i, j = 0;
|
|
|
|
char symbol, next;
|
2024-09-03 11:27:09 +05:30
|
|
|
for (i = 0; i < strlen(infix); i++)
|
|
|
|
{
|
2024-09-03 00:26:38 +05:30
|
|
|
symbol = infix[i];
|
2024-09-03 11:27:09 +05:30
|
|
|
if ((symbol >= 'a' && symbol <= 'z') || (symbol >= 'A' && symbol <= 'Z') || (symbol >= '0' && symbol <= '9'))
|
|
|
|
{
|
2024-09-03 00:26:38 +05:30
|
|
|
postfix[j++] = symbol;
|
2024-09-03 11:27:09 +05:30
|
|
|
}
|
|
|
|
else if (symbol == '(')
|
|
|
|
{
|
2024-09-03 00:26:38 +05:30
|
|
|
push(symbol);
|
2024-09-03 11:27:09 +05:30
|
|
|
}
|
|
|
|
else if (symbol == ')')
|
|
|
|
{
|
|
|
|
while ((next = pop()) != '(')
|
|
|
|
{
|
2024-09-03 00:26:38 +05:30
|
|
|
postfix[j++] = next;
|
|
|
|
}
|
2024-09-03 11:27:09 +05:30
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
while (top > -1 && precedence(stack[top]) >= precedence(symbol))
|
|
|
|
{
|
2024-09-03 00:26:38 +05:30
|
|
|
postfix[j++] = pop();
|
|
|
|
}
|
|
|
|
push(symbol);
|
|
|
|
}
|
|
|
|
}
|
2024-09-03 11:27:09 +05:30
|
|
|
while (top > -1)
|
|
|
|
{
|
2024-09-03 00:26:38 +05:30
|
|
|
postfix[j++] = pop();
|
|
|
|
}
|
|
|
|
postfix[j] = '\0';
|
|
|
|
}
|
|
|
|
|
2024-09-03 11:27:09 +05:30
|
|
|
int main()
|
|
|
|
{
|
2024-09-03 00:26:38 +05:30
|
|
|
char infix[MAX_SIZE], postfix[MAX_SIZE];
|
|
|
|
printf("Enter infix expression: ");
|
2024-09-03 11:27:09 +05:30
|
|
|
gets(infix);
|
2024-09-03 00:26:38 +05:30
|
|
|
infixToPostfix(infix, postfix);
|
|
|
|
printf("Postfix expression: %s\n", postfix);
|
|
|
|
return 0;
|
|
|
|
}
|