Here is a C++ program to convert postfix expression to fully parenthesized infix expression using stack.
C++ program to convert Postfix to Infix expression
#include<iostream>
using namespace std;
class infix
{
char post[30],stac[30],temp1[30],temp2[30];
int top,y,br1,br2;
public:
infix()
{
top=-1;y=0;
}
void convert()
{
int count=0,br;
for(int i=0;post[i]!=0;i++)
{
if(post[i]>96&post[i]<123)
{
stac[++top]=post[i];
}
else
{
if(stac[top]!=')')
pop2(temp1,br1);
else if(stac[top]==')')
pop1(temp1,br1);
if(stac[top]==')')
pop1(temp2,br2);
else
pop2(temp2,br2);
stac[++top]='(';
for(int z=0;z<br2;z++)
stac[++top]=temp2[z];
stac[++top]=post[i];
for(int z=0;z<br1;z++)
stac[++top]=temp1[z];
stac[++top]=')';
}
}
}
void pop1(char (&temp)[30],int &br)
{
br=0;
int z=top-1,count=1;
while(count!=0)
{
if(stac[z]==')')
count++;
else if(stac[z]=='(')
count--;
z--;
}
for(int i=z+1;i<=top;i++,br++)
temp[br]=stac[i];
top=z;
}
void pop2(char (&temp)[30],int &br)
{
br=0;
temp[br]=stac[top--];
br++;
}
void show()
{
cout<<"Infix expression : ";
for(int i=0;i<=top;i++)
cout<<stac[i];
}
void getdata()
{
cout<<"Enter Postfix expression : ";
cin.getline(post,30);
}
};
int main()
{
infix con;
con.getdata();
con.convert();
con.show();
return 0;
}
using namespace std;
class infix
{
char post[30],stac[30],temp1[30],temp2[30];
int top,y,br1,br2;
public:
infix()
{
top=-1;y=0;
}
void convert()
{
int count=0,br;
for(int i=0;post[i]!=0;i++)
{
if(post[i]>96&post[i]<123)
{
stac[++top]=post[i];
}
else
{
if(stac[top]!=')')
pop2(temp1,br1);
else if(stac[top]==')')
pop1(temp1,br1);
if(stac[top]==')')
pop1(temp2,br2);
else
pop2(temp2,br2);
stac[++top]='(';
for(int z=0;z<br2;z++)
stac[++top]=temp2[z];
stac[++top]=post[i];
for(int z=0;z<br1;z++)
stac[++top]=temp1[z];
stac[++top]=')';
}
}
}
void pop1(char (&temp)[30],int &br)
{
br=0;
int z=top-1,count=1;
while(count!=0)
{
if(stac[z]==')')
count++;
else if(stac[z]=='(')
count--;
z--;
}
for(int i=z+1;i<=top;i++,br++)
temp[br]=stac[i];
top=z;
}
void pop2(char (&temp)[30],int &br)
{
br=0;
temp[br]=stac[top--];
br++;
}
void show()
{
cout<<"Infix expression : ";
for(int i=0;i<=top;i++)
cout<<stac[i];
}
void getdata()
{
cout<<"Enter Postfix expression : ";
cin.getline(post,30);
}
};
int main()
{
infix con;
con.getdata();
con.convert();
con.show();
return 0;
}
No comments:
Post a Comment