fork download
  1. #include <iostream>
  2. #include <stack>
  3. using namespace std;
  4.  
  5. int precedence(char c)
  6. {
  7. if (c == '^') return 3;
  8. else if(c=='*'|| c=='/') return 2;
  9. else if(c=='+'|| c=='-') return 1;
  10. else return -1;
  11. }
  12.  
  13. string InfixToPostfix(string str)
  14. {
  15. stack<char>Stack;
  16. string result;
  17.  
  18. // add sentinal at end of infix exp
  19. str = str + ')';
  20.  
  21. Stack.push('(');
  22.  
  23. for (int i = 0; i<str.length(); i++)
  24. {
  25. char ch = str[i];
  26. if (isdigit(ch))
  27. {
  28. result += ch;
  29. }
  30. else if (ch == '(' )
  31. {
  32. Stack.push(ch);
  33. }
  34. else if(ch == ')')
  35. {
  36. while (Stack.top() != '(')
  37. {
  38. result += Stack.top();
  39. Stack.pop();
  40. }
  41. Stack.pop(); //Pop '('
  42. }
  43. else
  44. {
  45. while(!Stack.empty()) && (precedence(ch) <= precedence(Stack.top()))
  46. {
  47. result += Stack.top();
  48. Stack.pop();
  49. }
  50. Stack.push(ch);
  51. }
  52. }
  53. return result;
  54. }
  55.  
  56. int main()
  57. {
  58. string st = "(5*(6+2) - (2/4))";
  59. cout << "postfix exp"<< InfixToPostfix(st);
  60. return 0;
  61.  
  62. }
Success #stdin #stdout 0.02s 25692KB
stdin
1
2
10
42
11
stdout
#include <iostream>
#include <stack>
using namespace std;

int precedence(char c)
{
    if (c == '^')  return 3;
    else if(c=='*'|| c=='/') return 2;
    else if(c=='+'|| c=='-') return 1;
    else return -1;
}

string InfixToPostfix(string str)
{
    stack<char>Stack;
    string result;
    
    // add sentinal at end of infix exp
    str = str + ')';
    
    Stack.push('(');

    for (int i = 0; i<str.length(); i++) 
    {
        char ch = str[i];
        if (isdigit(ch))
        {
            result += ch;
        }
        else if (ch == '(' )
        {
            Stack.push(ch);
        }
        else if(ch == ')')
        {
            while (Stack.top() != '(')
            {
                result += Stack.top();
                Stack.pop();
            }
            Stack.pop(); //Pop '('
        }
        else
        {
            while(!Stack.empty()) && (precedence(ch) <= precedence(Stack.top()))
            {
                result += Stack.top();
                Stack.pop();
            }
            Stack.push(ch);
        }
    }
    return result;
}

int main()
{
    string st = "(5*(6+2) - (2/4))";
    cout << "postfix exp"<< InfixToPostfix(st);
    return 0;

}