Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. #include <iostream>
  2. #include <stack>
  3. #include <string>
  4. using namespace std;
  5.  
  6. int Priority(char c){
  7. if (c == '-' || c == '+')
  8. return 1;
  9. else if (c == '*' || c == '/')
  10. return 2;
  11. else if (c == '^')
  12. return 3;
  13. else
  14. return 0;
  15. }
  16.  
  17. //-------------------------------------------- For Priority of oparations
  18.  
  19. string infix_to_postfix(string exp){
  20. stack<char> stk;
  21. string output = "";
  22. //-------------------------------------------- For Create Empty stack
  23. for (int i = 0; i < exp.length(); i++){
  24. if (exp[i] == ' ') continue;
  25.  
  26. if (isdigit(exp[i]) || isalpha(exp[i]))
  27. output += exp[i];
  28. else if (exp[i] == '(')
  29. stk.push('(');
  30. else if (exp[i] == ')'){
  31. while (stk.top() != '('){
  32. output += stk.top();
  33. stk.pop();
  34. }
  35. stk.pop();
  36. }
  37. else{
  38. while (!stk.empty() && Priority(exp[i]) <= Priority(stk.top())){
  39. output += stk.top();
  40. stk.pop();
  41. }
  42. stk.push(exp[i]);
  43. }
  44. }
  45.  
  46. while (!stk.empty()){
  47. output += stk.top();
  48. stk.pop();
  49. }
  50.  
  51. return output;
  52. }
  53. //-------------------------------------------- :)
  54. int main()
  55. {
  56. string infixExpression;
  57. cout << "Enter The infix Expressions: ";
  58. cin >> infixExpression ;
  59. cout <<"The Postfix Expressions is: "<< infix_to_postfix(infixExpression) << endl;
  60. return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement