Here is a C++ program to convert infix expression to prefix expression using stack.
C++ program to convert infix to prefix expression
#include<iostream>
#include<string.h>
using namespace std;
class prefix
{
char pre[30],inf[30],stac[30];
int top,y;
public:
prefix()
{
top=-1;y=0;
}
void convert()
{
strrev(inf);
for(int i=0;inf[i]!=0;i++)
{
if(inf[i]>=97&&inf[i]<=122)
pre[y++]=inf[i];
else
{
switch(inf[i])
{
case '+':
case '-':
while(top>=0&&stac[top]!=')'&&stac[top]!='+'&&stac[top]!='-')
pre[y++]=stac[top--];
stac[++top]=inf[i];
break;
case '*':
case '/':
while(stac[top]=='^'&&top>=0&&stac[top]!=')')
pre[y++]=stac[top--];
stac[++top]=inf[i];
break;
case '^':
stac[++top]=inf[i];
break;
case ')':
stac[++top]=inf[i];
break;
case '(':
while(stac[top]!=')')
pre[y++]=stac[top--];
top--;
break;
}
}
}
while(top>=0)
pre[y++]=stac[top--];
}
void show()
{
cout<<"Prefix expression : ";
for(int i=y-1;i>=0;i--)
cout<<pre[i];
}
void getdata()
{
cout<<"Enter Infix expression : ";
cin.getline(inf,30);
}
};
int main()
{
prefix con;
con.getdata();
con.convert();
con.show();
return 0;
}
#include<string.h>
using namespace std;
class prefix
{
char pre[30],inf[30],stac[30];
int top,y;
public:
prefix()
{
top=-1;y=0;
}
void convert()
{
strrev(inf);
for(int i=0;inf[i]!=0;i++)
{
if(inf[i]>=97&&inf[i]<=122)
pre[y++]=inf[i];
else
{
switch(inf[i])
{
case '+':
case '-':
while(top>=0&&stac[top]!=')'&&stac[top]!='+'&&stac[top]!='-')
pre[y++]=stac[top--];
stac[++top]=inf[i];
break;
case '*':
case '/':
while(stac[top]=='^'&&top>=0&&stac[top]!=')')
pre[y++]=stac[top--];
stac[++top]=inf[i];
break;
case '^':
stac[++top]=inf[i];
break;
case ')':
stac[++top]=inf[i];
break;
case '(':
while(stac[top]!=')')
pre[y++]=stac[top--];
top--;
break;
}
}
}
while(top>=0)
pre[y++]=stac[top--];
}
void show()
{
cout<<"Prefix expression : ";
for(int i=y-1;i>=0;i--)
cout<<pre[i];
}
void getdata()
{
cout<<"Enter Infix expression : ";
cin.getline(inf,30);
}
};
int main()
{
prefix con;
con.getdata();
con.convert();
con.show();
return 0;
}
pls check again at C++shell
ReplyDelete