Skip to main content

Infix to Postfix

Task: Convert the given string from Infix to Postfix.
Example:
Input:
1
A*(B+C)/D
Output:
ABC+*D/

Here is the Code:
Program in C++:
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. int prec(char c)
  5. {
  6.     if(c=='^')
  7.     {
  8.         return 3;
  9.     }
  10.     else if(c=='*'||c=='/')
  11.     {
  12.         return 2;
  13.     }
  14.     else if(c=='+'||c=='-')
  15.     {
  16.         return 1;
  17.     }
  18.     else
  19.     {
  20.         return -1;
  21.     }
  22. }
  23. int infixToPostfix(string s)
  24. {
  25.     stack<char> st;
  26.     for(int i=0;i<s.length();i++)
  27.     {
  28.         if(isalpha(s[i]))
  29.         {
  30.             cout<<s[i];
  31.         }
  32.         else if(s[i]==')')
  33.         {
  34.             while(st.top()!='(')
  35.             {
  36.                 cout<<st.top();
  37.                 st.pop();
  38.             }
  39.             st.pop();
  40.         }
  41.         else
  42.         {
  43.             if(st.empty()==true)
  44.             {
  45.                 st.push(s[i]);
  46.             }
  47.             else
  48.             {
  49.                 if(s[i]=='('||st.top()=='('||prec(s[i])>prec(st.top()))
  50.                 {
  51.                     st.push(s[i]);
  52.                 }
  53.                 else
  54.                 {
  55.                     while(st.empty()==false&&prec(s[i])<=prec(st.top())&&st.top()!='(')
  56.                     {
  57.                         cout<<st.top();
  58.                         st.pop();
  59.                     }
  60.                     st.push(s[i]);
  61.                 }
  62.             }
  63.         } 
  64.     } 
  65.     while(st.empty()==false)
  66.     {
  67.         cout<<st.top();
  68.         st.pop();
  69.     }
  70. }
  71. int main()
  72.  {
  73. int t;
  74. cin>>t;
  75. while(t--)
  76. {
  77.     string str;
  78.     getline(cin, str);
  79.     infixToPostfix(str);
  80.     cout<<endl;
  81. }
  82. return 0;
  83. }         

Here is the Video: