You are on page 1of 2

#include<bits/stdc++.

h>
using namespace std;
int priority(char c)
{
if(c=='*' || c=='/')
return 1;
else if(c=='+' || c=='-')
return 2;
}
bool isOperator(char c)
{
if(c == '+' || c=='-' || c=='*' || c=='/')
return true ;
else
return false ;
}
string infix_to_postfix(string s)
{
s = "("+s+")" ;
stack<char> st ;
string ans = "" ;
for(int i=0;i<s.size();i++)
{
if(s[i] == '(')
st.push(s[i]) ;
else if(!isOperator(s[i]) && s[i] != ')')
{
string x(1,s[i]);
ans+=x;
}
else if(isOperator(s[i]))
{
char x = st.top() ;
if(isOperator(x))
{
if(priority(x)<priority(s[i]))
{
string ch(1,x);
ans+=ch ;
st.pop() ;
st.push(s[i]);
}
else
{
st.push(s[i]);
}
}
else
st.push(s[i]);
}
else if(s[i] == ')')
{
while(st.top() != '(')
{
char x = st.top() ;
string ch(1,x) ;
ans+=ch ;
st.pop() ;
}
st.pop() ;
}
}

return ans ;
}
bool check(string s)
{
if(isOperator(s[0])||isOperator(s[1]))
return false ;
if(!isOperator(s[s.size()-1]))
return false ;
int operators = 0 ;
int operands = 0 ;
for(int i=0;i<s.size();i++)
{
if(isOperator(s[i]))
operators++ ;
else
operands++ ;
}
if(operands-operators != 1)
return false ;
return true;
}
int main()
{
string s ;
cout<<"Enter the In-Fix Expression : " ;
cin>>s ;
bool ans = check(infix_to_postfix(s)) ;
if(ans)
cout<<endl<<"The Given In-Fix Expression is VALID"<<endl ;
else
cout<<endl<<"The Given In-Fix Expression is NOT VALID"<<endl ;
return 0 ;
}

You might also like