Advertisement
urmisaha

Infix to Postfix

Oct 28th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int T;
  5. string S;
  6.  
  7. bool operand(char x){
  8.     if(int(x) >= 65 && int(x) <= 90)
  9.         return true;
  10.     if(int(x) >= 97 && int(x) <= 122)
  11.         return true;
  12.     return false;
  13. }
  14.  
  15. int prec(char x){
  16.     if(x == '^')
  17.         return 3;
  18.     if(x == '*' || x == '/')
  19.         return 2;
  20.     if(x == '-' || x == '+')
  21.         return 1;
  22.     return 0;
  23. }
  24.  
  25. int main()
  26. {
  27.     cin>>T;
  28.     while(T--){
  29.         cin>>S;
  30.         stack<char> st;
  31.         string res = "";
  32.         for(int i=0; i<S.length(); ++i){
  33.             if(operand(S[i]))
  34.                 res += S[i];
  35.             else{
  36.                 if(S[i] == ')'){
  37.                     while(st.top() != '('){
  38.                         res += st.top();
  39.                         st.pop();
  40.                     }
  41.                     st.pop();
  42.                 }
  43.                 else if(st.empty() || prec(st.top()) < prec(S[i]) || S[i] == '(')
  44.                     st.push(S[i]);
  45.                 else{
  46.                     while(!st.empty() && prec(st.top()) >= prec(S[i])){
  47.                         res += st.top();
  48.                         st.pop();
  49.                     }
  50.                     st.push(S[i]);
  51.                 }
  52.             }
  53.         }
  54.         while(!st.empty()){
  55.             res += st.top();
  56.             st.pop();
  57.         }
  58.         cout<<res<<endl;
  59.     }
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement