Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- int prec(char c)
- {
- if(c=='^')
- return 5;
- else if(c == '/')
- return 4;
- else if(c == '*')
- return 3;
- else if(c == '-')
- return 2;
- else if(c == '+')
- return 1;
- else
- return -1;
- }
- void infixToPostfix(string s)
- {
- stack<char> st;
- int l = s.length();
- string ns;
- for(int i = 0; i < l; i++)
- {
- if((s[i] >= 'a' && s[i] <= 'z')||(s[i] >= 'A' && s[i] <= 'Z'))
- ns+=s[i];
- else if(s[i]=='('||s[i]=='{'||s[i]=='[')
- st.push(s[i]);
- else if(s[i]==')'||s[i]=='}'||s[i]==']')
- {
- while(!st.empty()&&((s[i]==')'&&st.top()!='(')||(s[i]=='}'&&st.top()!='{')||(s[i]==']'&&st.top()!='[')))
- {
- ns+=st.top();
- st.pop();
- }
- st.pop();
- }
- else
- {
- while(!st.empty() && prec(s[i]) <= prec(st.top()))
- {
- char c = st.top();
- st.pop();
- ns += c;
- }
- st.push(s[i]);
- }
- }
- while(!st.empty())
- {
- char c = st.top();
- st.pop();
- ns += c;
- }
- cout << ns << endl;
- }
- int main()
- {
- int t;
- cin>>t;
- for(int i=0; i<t; i++)
- {
- string exp;
- cin>>exp;
- infixToPostfix(exp);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement