#include<iostream>
#include<string>
using namespace std;
class stack
{
string item;
int top;
public:
stack()
{
top=-1;
}
void push(char ch)
{
top++;
item[top]=ch;
}
char pop()
{
char ele;
if(isempty())
{
printf("\n stack overflow!!");
return '@';
}
ele=item[top];
top--;
return ele;
}
char peep()
{
return(item[top]);
}
int isempty()
{
if(top==-1)
return 1;
return 0;
}
int priority(char ch)
{
if(ch==')')
return 1;
else if(ch=='+' || ch=='-')
return 2;
else if(ch=='*' || ch=='/')
return 3;
else
return 4;
}
};
int main()
{
string infix,prefix;
char ch,ch2,token,temp;
int i,j=0,len;
stack st;
cout<<"enter the valid infix expression: ";
cin>>infix;
len=infix.size();
for(i=len-1;i>=0;i--)
{
token=infix[i];
if(token==')')
st.push(token);
else if(token=='(')
{
ch=st.pop();
while(ch!=')')
{
prefix.push_back(ch);
ch=st.pop();
}
}
else if(token=='+' || token=='-' || token=='*' || token=='/' || token=='^')
{
ch2=st.peep();
while(!st.isempty() && st.priority(token)<st.priority(ch2))
{
ch=st.pop();
prefix.push_back(ch);
ch2=st.peep();
}
st.push(token);
}
else
st.push(token);
}
while(!st.isempty())
{
ch=st.pop();
prefix.push_back(ch);
}
cout<<"\n The Corresponding Prefix Expression is:";
for(j = prefix.size() - 1;j>=0;j--)
{
cout<<prefix[j];
}
return 0;
}
// I am trying to change this to C program languge if possiable .