CONVERTING INFIX EXPRESSION INTO POSTFIX EXPRESSION.
///PROGRAM TO CONVERT INFIX EXPRESSION INTO POSTFIX EXPRESSION.//
#include <iostream>
#include <string.h>
#include <cctype>
#include <stdlib.h>
#include <conio.h>
using namespace std;
template <class Type>
class Infix2Postfix
{
private:
Type *Stack;
int Size, Top;
public:
Infix2Postfix(int Siz)
{
Size = Siz;
Stack = new Type[Size];
strcpy(Stack, "\0");
Top = -1;
}
void Push(Type Ch)
{
if( IsFull() )
{
cout << "\nSTACK OVERFLOWED!!!!!!!!!\n" << endl;
exit(1);
}
Stack[++Top] = Ch;
}
Type Pop()
{
if( IsEmpty() )
{
cout << "\nSTACK UNDERFLOWED!!!!!!\n" << endl;
exit(1);
}
return Stack[Top--];
}
Type TOP()
{
return Stack[Top];
}
bool IsOperator(char Ch)
{
return ( !isalpha(Ch) && !isdigit(Ch) );
}
int Priority(char Ch)
{
if (Ch == '^')
return 3;
else if( Ch == '*' || Ch == '/' )
return 2;
else if(Ch == '+' || Ch == '-')
return 1;
return 0;
}
string Convert(string Infix)
{
char Ch;
string Postfix;
for(int I =0; I <Infix.length(); I++)
{
Ch = Infix[I];
if( isalpha(Ch) || isdigit(Ch) )
Postfix += Ch;
else if( Ch == '(' )
Push(Ch);
else if( Ch == ')' )
{
while(TOP() !='(')
{
Postfix += Pop();
}
Pop();
}
else
{
if(IsOperator( TOP() ) )
{
while( Priority(Ch) <= Priority( TOP() ) )
Postfix += Pop();
Push(Ch);
}
}
}
while(!IsEmpty())
Postfix += Pop();
return Postfix;
}
inline bool IsFull()
{
return (Top == Size - 1);
}
inline bool IsEmpty()
{
return (Top == -1);
}
~Infix2Postfix()
{
cout << "\n\n\n****************PROGRAM ENDED*******************\n\n\n" << endl;
}
};
int main()
{
Infix2Postfix<char> Obj(100);
string Expression;
cout << "Enter any INFIX Expression: ";
cin >> Expression;
cout << "\nExpression After Converting To POSTFIX is: " << Obj.Convert(Expression) << endl;
getch();
return 0;
}
0 comments:
Post a Comment