Infix to Prefix conversion of an expression
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<queue>
#include<stack>
using namespace std;
class infixtoprefix
{
int len;
char strn[100];
stack<char> stackk;
stack<char> strng;
public:
infixtoprefix()
{
cin>>strn;
len=strlen(strn);
}
int priority(char a)
{
if(a=='*'||a=='/')
{
return 2;
}
else if(a=='+'||a=='-')
{
return 1;
}
return 0;
}
int convert()
{
int i=len-1;
while(i>=0)
{
///case 1
if(isalpha(strn[i])||isdigit(strn[i])) // if its an alphabet or digit i.ie., a to z and 1 to 9
{
strng.push(strn[i]);
}
///case 2
else if(strn[i]=='(')
{
while(stackk.top()!=')')
{
strng.push(stackk.top());
stackk.pop();
}
stackk.pop();
}
///case 3
else //if its an operator i.e., +,-,*,/
{
if(stackk.empty()||(priority(stackk.top())<priority(strn[i]))) //if stack is empty or priority of element in stack is lower
{
stackk.push(strn[i]);
}
else
{
while(!stackk.empty()&&strn[i]!=')'&&priority(stackk.top())>priority(strn[i]))
{
strng.push(stackk.top());
stackk.pop();
}
stackk.push(strn[i]);
}
}
i--;
}
while(!stackk.empty())
{
strng.push(stackk.top());
stackk.pop();
}
}
void display()
{
while(!strng.empty())
{
cout<<strng.top();
strng.pop();
}
}
};
int main()
{
infixtoprefix *obj = new infixtoprefix();
obj->convert();
obj->display();
}
Comments
Post a Comment