Write a program to convert the given infix expression into its postfix form


#include
#include
#include
#include

int TOP = -1, rank = 0;
char STACK[50];

class infix_exp
{
public:
void PUSH(char item);
char POP();
int F(char symbol);
int G(char symbol);
int RANK(char symbol);
int infix_postfix(char infix[ ], char postfix[ ]);
};


void infix_exp::PUSH(char item)
{
TOP++;
STACK[TOP] = item;
}

char infix_exp::POP()
{
return STACK[TOP--];
}

int infix_exp::F(char symbol)
{
switch (symbol)
{
case '+':
case '-': return 1;
case '*':
case '/': return 3;
case '^': return 6;
case '(': return 9;
case ')': return 0;
default: return 7;
}
}

int infix_exp::G(char symbol)
{
switch (symbol)
{
case '+':
case '-': return 2;
case '*':
case '/': return 4;
case '^': return 5;
case '(': return 0;
case '#': return -1;
default: return 8;
}
}

int infix_exp::RANK(char symbol)
{
switch (symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^': return -1;
default: return 1;
}
}

int infix_exp::infix_postfix(char infix[50], char postfix[50])
{
int length, i, j = 0;
char ch, temp;
length = strlen(infix);
PUSH('#');

for (i=0 ;i
{
ch = infix[i];
while (F(ch)
{
temp = POP();
rank += RANK(temp);
if (rank<1 font="font">
{
return -1;
}
postfix[j++] = temp;
}
if (F(ch)!=G(STACK[TOP]))
{
PUSH(ch);
}
else
POP();
}
while (STACK[TOP]!='#')
{
temp = POP();
rank += RANK(temp);
if (rank<1 font="font">
{
return -1;
}
postfix[j++] = temp;
}
postfix[j] = '\0';
return rank;
}

void main()
{
char infix[50], postfix[50];
infix_exp obj;
clrscr();
cout << "\nEnter a valid infix expression : " ;
gets(infix);
rank = obj.infix_postfix(infix, postfix);
if (rank==1)
{
cout << "\nPostfix expression is : " << postfix;
}
else
cout << "\nInvalid infix expression" ;
getch();
}

Comments

Popular posts from this blog

To convert hexadecimal to decimal numbers.

To convert hexadecimal to decimal numbers.