2017-09-19 10:44:51 +05:30
|
|
|
//convert infix to postfix
|
|
|
|
#include <stdio.h>
|
|
|
|
char stack[20]; //declaring an empty stack
|
|
|
|
int top = -1; //declaring top of stack
|
|
|
|
|
|
|
|
void push(char x) //push function
|
2017-08-25 22:07:06 +05:30
|
|
|
{
|
2017-09-19 10:44:51 +05:30
|
|
|
stack[++top] = x; //each time it is pushed top is increamented
|
2017-08-25 22:07:06 +05:30
|
|
|
}
|
2017-09-19 10:44:51 +05:30
|
|
|
|
|
|
|
char pop() //pop function
|
2017-08-25 22:07:06 +05:30
|
|
|
{
|
|
|
|
if(top == -1)
|
|
|
|
return -1;
|
|
|
|
else
|
2017-09-19 10:44:51 +05:30
|
|
|
return stack[top--]; //each time it is popped top is decreamented
|
2017-08-25 22:07:06 +05:30
|
|
|
}
|
2017-09-19 10:44:51 +05:30
|
|
|
|
|
|
|
int priority(char x) // to check the priority of characters
|
2017-08-25 22:07:06 +05:30
|
|
|
{
|
|
|
|
if(x == '(')
|
|
|
|
return 0;
|
|
|
|
if(x == '+' || x == '-')
|
|
|
|
return 1;
|
|
|
|
if(x == '*' || x == '/')
|
|
|
|
return 2;
|
|
|
|
if(x=='^')
|
|
|
|
return 3;
|
|
|
|
}
|
|
|
|
|
|
|
|
int main()
|
|
|
|
{
|
|
|
|
char exp[20];
|
|
|
|
char *e, x;
|
|
|
|
printf("Enter the expression :: ");
|
|
|
|
scanf("%s",exp);
|
|
|
|
e = exp;
|
|
|
|
while(*e != '\0')
|
|
|
|
{
|
|
|
|
if(isalnum(*e))
|
|
|
|
printf("%c",*e);
|
2017-09-19 10:44:51 +05:30
|
|
|
else if(*e == '(') //push it directly into the stack
|
2017-08-25 22:07:06 +05:30
|
|
|
push(*e);
|
2017-09-19 10:44:51 +05:30
|
|
|
else if(*e == ')') //pop until we gwt the left parenthesis
|
2017-08-25 22:07:06 +05:30
|
|
|
{
|
|
|
|
while((x = pop()) != '(')
|
|
|
|
printf("%c", x);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2017-09-19 10:44:51 +05:30
|
|
|
while(priority(stack[top]) >= priority(*e)) //pop until priority of top of stack is greater than equal to priority of expressions character
|
2017-08-25 22:07:06 +05:30
|
|
|
printf("%c",pop());
|
2017-09-19 10:44:51 +05:30
|
|
|
push(*e); //otherwise push
|
2017-08-25 22:07:06 +05:30
|
|
|
}
|
|
|
|
e++;
|
|
|
|
}
|
2017-09-19 10:44:51 +05:30
|
|
|
// keep popping until top is not -1
|
2017-08-25 22:07:06 +05:30
|
|
|
while(top != -1)
|
|
|
|
{
|
2017-09-19 10:44:51 +05:30
|
|
|
printf("%c",pop());
|
2017-08-25 22:07:06 +05:30
|
|
|
}
|
|
|
|
}
|