67% found this document useful (3 votes)
833 views2 pages

1.check Valid Infix Expression

The document contains C++ code to convert an infix expression to postfix notation. It defines functions to determine operator priority, check if a character is an operator, perform the conversion to postfix, and check if a postfix expression is valid. The main function gets an infix expression from the user, converts it to postfix, and checks if the postfix expression is valid.

Uploaded by

Yashika Aggarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
67% found this document useful (3 votes)
833 views2 pages

1.check Valid Infix Expression

The document contains C++ code to convert an infix expression to postfix notation. It defines functions to determine operator priority, check if a character is an operator, perform the conversion to postfix, and check if a postfix expression is valid. The main function gets an infix expression from the user, converts it to postfix, and checks if the postfix expression is valid.

Uploaded by

Yashika Aggarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 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