#include <iostream> using namespace std; class InToPost { char *infx,*pofx,*s,ch,elem; int top,size; int i,j; char temp; public: void push(char elem); char pop(); void convert(); int prec(char elem); InToPost() { top = -1; cout<<"enter size of the string"<<endl; cin>>size; infx=new char[size]; pofx=new char[size]; s=new char[size]; cout<<"read the infix expression ? "; cin>>infx; } }; void InToPost::push(char elem) { s[top] = elem; top++; } char InToPost:: pop() { top--; return (s[top]); } /* Write code in convert() to convert infix to postfix expr */ int InToPost::prec(char elem) { if(elem=='(') { return 1; } if(elem=='+'||elem=='-') { return 2; } if(elem=='*'||elem=='/') { return 3; } } void InToPost::convert() { for(i=0;i<size;i++) { if(infx[i]!='+'&&infx[i]!='-'&&infx[i]!='*'&&infx[i]!='/'&&infx[i]!='(') { pofx[j++]=infx[i]; } else { if(top==0) { push(infx[i]); } else { if(infx[i]!='(') { if(prec(infx[i])<=prec(s[top-1])) { temp=pop(); pofx[j++]=temp; push(infx[i]); } else { push(infx[i]); } } else { if(infx[i]=='(') { push(infx[i]); } } } } } while(top!=0) { pofx[j++]=pop(); } cout<<infx<<endl; cout<<pofx<<endl; } /* Write code here to find the precedence of the operators as indicated below # = 0, ( = 1, +,- = 2, *,/ = 3 using function int prec(char elem); */ int main() { char ch; int i = 0, k = 0; InToPost ip; ip.push('#'); ip.convert(); return 0; }
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy. Accept Learn more