Here is a C++ program to convert infix to postfix expression using stack.
C++ program to convert infix to postfix
#include<iostream>
using namespace std;
class postfix
{
char post[30],inf[30],stac[30];
int top,y;
public:
postfix()
{
top=-1;y=0;
}
void convert()
{
for(int i=0;inf[i]!=0;i++)
{
if(inf[i]>=48&&inf[i]<=57)
post[y++]=inf[i];
else
{
switch(inf[i])
{
case '+':
case '-':
while(top>=0&&stac[top]!='(')
post[y++]=stac[top--];
stac[++top]=inf[i];
break;
case '*':
case '/':
while(stac[top]!='+'&&stac[top]!='-'&&top>=0&&stac[top]!='(')
post[y++]=stac[top--];
stac[++top]=inf[i];
break;
case '^':
stac[++top]=inf[i];
break;
case '(':
stac[++top]=inf[i];
break;
case ')':
while(stac[top]!='(')
post[y++]=stac[top--];
top--;
break;
}
}
}
while(top>=0)
post[y++]=stac[top--];
}
void show()
{
for(int i=0;i<y;i++)
cout<<post[i];
}
void getdata()
{
cout<<"Enter expression : ";
cin.getline(inf,30);
}
};
int main()
{
postfix con;
con.getdata();
con.convert();
con.show();
return 0;
}
using namespace std;
class postfix
{
char post[30],inf[30],stac[30];
int top,y;
public:
postfix()
{
top=-1;y=0;
}
void convert()
{
for(int i=0;inf[i]!=0;i++)
{
if(inf[i]>=48&&inf[i]<=57)
post[y++]=inf[i];
else
{
switch(inf[i])
{
case '+':
case '-':
while(top>=0&&stac[top]!='(')
post[y++]=stac[top--];
stac[++top]=inf[i];
break;
case '*':
case '/':
while(stac[top]!='+'&&stac[top]!='-'&&top>=0&&stac[top]!='(')
post[y++]=stac[top--];
stac[++top]=inf[i];
break;
case '^':
stac[++top]=inf[i];
break;
case '(':
stac[++top]=inf[i];
break;
case ')':
while(stac[top]!='(')
post[y++]=stac[top--];
top--;
break;
}
}
}
while(top>=0)
post[y++]=stac[top--];
}
void show()
{
for(int i=0;i<y;i++)
cout<<post[i];
}
void getdata()
{
cout<<"Enter expression : ";
cin.getline(inf,30);
}
};
int main()
{
postfix con;
con.getdata();
con.convert();
con.show();
return 0;
}
No comments:
Post a Comment