Here is a C++ program to convert postfix expression to fully parenthesized infix expression using stack.
C++ program to convert prefix to infix
#include<iostream>
#include<string.h>
using namespace std;
class infix
{
char pre[30],stac[30],temp1[30],temp2[30];
int top,y,br1,br2;
public:
infix()
{
top=-1;y=0;
}
void convert()
{
int count=0,br;
strrev(pre);
for(int i=0;pre[i]!=0;i++)
{
if(pre[i]>96&pre[i]<123)
{
stac[++top]=pre[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<br1;z++)
stac[++top]=temp1[z];
stac[++top]=pre[i];
for(int z=0;z<br2;z++)
stac[++top]=temp2[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 prefix expression : ";
cin.getline(pre,30);
}
};
int main()
{
infix con;
con.getdata();
con.convert();
con.show();
return 0;
}
#include<string.h>
using namespace std;
class infix
{
char pre[30],stac[30],temp1[30],temp2[30];
int top,y,br1,br2;
public:
infix()
{
top=-1;y=0;
}
void convert()
{
int count=0,br;
strrev(pre);
for(int i=0;pre[i]!=0;i++)
{
if(pre[i]>96&pre[i]<123)
{
stac[++top]=pre[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<br1;z++)
stac[++top]=temp1[z];
stac[++top]=pre[i];
for(int z=0;z<br2;z++)
stac[++top]=temp2[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 prefix expression : ";
cin.getline(pre,30);
}
};
int main()
{
infix con;
con.getdata();
con.convert();
con.show();
return 0;
}
There is an error on the strrev(pre);
ReplyDeleteSaying strrev was not declared
ami kichu buji na kn!?
ReplyDelete