#include<iostream>
#include<string>
#include<stack>
using namespace std;
int getweight(char c)
{
switch(c)
{
case '^' : return 3;
break;
case '*' :
case '/' : return 2;
break;
case '+' :
case '-' : return 1;
break;
default : return 0;
}
}
void infix2postfix(char infix[], char postfix[], int size ,int sizepos)
{
stack <char> s;
int i = 0;
int j = 0;
int weight = 0;
char ch;
while( i < size)
{
ch = infix[i];
//cout<<i<<endl;
// cout<<ch<<endl;
if ( ch == '(' )
{
s.push(ch);
i++;
continue;
}
else if( ch == ')')
{
if(s.top() == '(')
{
s.pop();
}
else
{
while(s.top() != '(')
{
postfix[j++] = s.top();
s.pop();
}
s.pop();
i++;
continue;
}
}
else
{
weight = getweight(ch);
if(weight == 0)
{
postfix[j++] = ch;
}
else if(s.empty())
{
s.push(ch);
}
else if(getweight(s.top()) < weight)
{
s.push(ch);
}
else
{
if(getweight(s.top()) >= weight )
{
postfix[j++] = s.top();
s.pop();
}
s.push(ch);
}
}
i++;
}
while(!s.empty())
{
if(getweight(s.top())!= 0)
{ postfix[j++] = s.top();
s.pop();
}
}
for(int i = 0 ; i < sizepos ; i++)
cout<<postfix[i];
}
int main()
{
char infix[25];
cout<<"ENTER THE INFIX EXPRESSION \t=\t";
cin>>infix;
int size = 0,sizepos = 0;
for( int i = 0 ; infix[i] != '\0' ; i++)
{
size++;
if( infix[i] != '(' && infix[i] != ')')
sizepos++;
}
cout<<"size:"<<size<<endl;
char postfix[sizepos];
infix2postfix(infix, postfix, size,sizepos);
return 0;
}
Comments
Post a Comment