Infix to Postfix Expression
Infix to Postfix Expression
PROBLEM STATEMENT :
SOLUTION :
#include <bits/stdc++.h>
int priority(char c)
{
if(c=='+'||c=='-') return 1;
else if(c=='*'||c=='/') return 2;
else if(c=='^') return 3;
return -1;
}
using namespace std;
int main() {
int t,i;
cin>>t;
stack<char> st;
while(t--)
{
string s;
cin>>s;
for(i=0;i<s.size();++i)
{
if(isalnum(s[i]))
{
cout<<s[i];
}
else if(s[i]=='(')
{
st.push(s[i]);
}
else if(s[i]==')')
{
while(st.top()!='(')
{
cout<<st.top();
st.pop();
}
st.pop();
}
else
{
while(priority(st.top())>=priority(s[i]))
{
cout<<st.top();
st.pop();
}
st.push(s[i]);
}
}
while(!st.empty())
{
cout<<st.top();
st.pop();
}
cout<<"\n";
}
return 0;
}
Comments
Post a Comment