Advertisement
29rohitkr

Postfix Evaluation Using Stack

Feb 22nd, 2023
920
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <stack>
  4.  
  5. using namespace std;
  6.  
  7. // Function to evaluate postfix
  8. // expressions
  9. int evaluatePostfix(string str)
  10. {
  11.     // Creating an empty stack
  12.     stack<int> st;
  13.     int n = str.length();
  14.  
  15.     // Traversing the string
  16.     for (int i = 0; i < n; i++) {
  17.         // Pushing elements into stack
  18.         // if element is a number
  19.         if (isdigit(str[i]))
  20.             st.push(str[i] - '0');
  21.  
  22.         // Evaluation of the expression
  23.         else {
  24.             int val1 = st.top();
  25.             st.pop();
  26.             int val2 = st.top();
  27.             st.pop();
  28.             char op = str[i];
  29.  
  30.             // Checking for the operators
  31.             switch (op) {
  32.             case '+':
  33.                 st.push(val2 + val1);
  34.                 break;
  35.             case '-':
  36.                 st.push(val2 - val1);
  37.                 break;
  38.             case '*':
  39.                 st.push(val2 * val1);
  40.                 break;
  41.             case '/':
  42.                 st.push(val2 / val1);
  43.                 break;
  44.             }
  45.         }
  46.     }
  47.     return st.top();
  48. }
  49.  
  50. // Drivers Method
  51. int main()
  52. {
  53.     string str = "231*+9-";
  54.     cout << evaluatePostfix(str) << endl;
  55.  
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement