How to convert infix expression into prefix expression in c++

/* Convert Infix Expression into Prefix Using Stack
Steps for Conversion :
1. Reverse the String/Expression
2.Reverse the brackets means ( into ) and vice versa
3. convert expression into postfix
4. reverse the postfix expression
5. This is your required prefix Expression
*/                                                                                                                                        

Here is the code copy it and pastte it on any online or offline compiler

#include<iostream> using namespace std;
class exp{
private :
int top1, top2,top3;
char ch,stack1[30],stack2[30],stack3[30],st[30];
public:
exp(){
top1=-1;
top2=-1;
top3=-1;
}
void input(){
cout<<“Enter the infix expression “;
cin.getline(st,30);
}
void revstring(){
for(int i=0; st[i]!=’\0′;i++)
{
if(st[i]=='(‘)
stack1[++top1]=’)’;
else if(st[i]==’)’)
stack1[++top1]='(‘;
else
stack1[++top1]=st[i];
}
}
void display(){
while(top3!=-1){
cout<<stack3[top3]<<” “;
top3–;

        }
    }
    void push(){
        stack2[++top2]=ch;
    }
    void pop(){
        while(top2!=-1) {
        if(ch==')'){
            stack3[++top3]=stack2[top2--];
            if(stack2[top2]=='('){
                top2--;
                break;
            }
        }
        else
        {
            stack3[++top3]=stack2[top2--];
            if(stack2[top2]=='(')
            break;
        }
    }}
    void scan(){
        revstring();
        while(top1!=-1){
            ch=stack1[top1--];
            if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch==')'||ch=='('){
                if(ch=='(') push();
                else if(ch==')') pop();
                else if(stack2[top2]=='(') push();
                else if(top2==-1) push();
                else if((stack2[top2]=='+'||stack2[top2]=='-')&&(ch=='*'||ch=='/'))
                push();
                else
                {
                push();
                pop();
                }
            }
            else{
                stack3[++top3]=ch;
            }
        }
        pop();
        display() ;
    }

};
int main(){
exp obj;
obj.input();
cout<<endl;
obj.scan();
return 0;
}

One Reply to “How to convert infix expression into prefix expression in c++”

  1. Usually I do not read post on blogs, but I would like to say that this write-up very forced me to try and do so! Your writing style has been amazed me. Thanks, very nice post.

Leave a Reply

Your email address will not be published. Required fields are marked *