Advertisement
carlos1993

Prefix to Postfix

Sep 30th, 2013
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.85 KB | None | 0 0
  1. */
  2.  
  3. #include <cstdlib>
  4. #include <iostream>
  5. #include <string>
  6.  
  7. #include<map>
  8. using namespace std;
  9.  
  10. /*
  11.  *
  12.  */
  13.  
  14.  
  15. class post {
  16. private:
  17.     string stack;
  18.  
  19.     string prefix;
  20.     map<char, int> op;
  21.  
  22. public:
  23.     string postfix;
  24.  
  25.     post(string pre) : prefix(pre) {
  26.         stack.clear();
  27.         //Operator value table
  28.         op['-'] = 1;
  29.         op['+'] = 2;
  30.         op['/'] = 3;
  31.         op['*'] = 4;
  32.         op['^'] = 5;
  33.         op[')'] = -1;
  34.         op['('] = -1;
  35.     }
  36.  
  37.     void scan() {
  38.         for (int i = 0; i < prefix.length(); i++) {
  39.             if (isdigit(prefix[i])) {
  40.                 postfix += prefix[i];
  41.             } else if(prefix[i] != ' ') {
  42.                 checkStack(prefix[i]);
  43.             }
  44.         }
  45.         for (int i = stack.length(); i >= 0; i--) {
  46.             if (op[stack[i]] != -1)
  47.                 postfix += stack[i];
  48.         }
  49.  
  50.     }
  51.  
  52.     void checkStack(char sym) {
  53.         int i = stack.length() - 1;
  54.         int newsym = op[sym];
  55.         cout << stack << endl;
  56.  
  57.         if (stack.empty()) {
  58.             stack += sym;
  59.             return;
  60.         } else {
  61.             if (newsym > op[stack[i]]) {
  62.                 stack += sym; //push
  63.                 return;
  64.             } else {
  65.                 while (newsym <= op[stack[i]]) {
  66.                     if (op[stack[i]] != -1)
  67.                         postfix += stack[i]; //pop in to the postfix expression
  68.                     stack.erase(stack.end() - 1); //pop out the stack
  69.                     i--;
  70.                     if (stack.empty())
  71.                         break;
  72.                 }
  73.                 stack += sym; //push
  74.             }
  75.  
  76.         }
  77.  
  78.     }
  79.  
  80. };
  81.  
  82. int main(int argc, char** argv) {
  83.  
  84.     string prefix = "(5+3)*12/3";
  85.     post postfix(prefix);
  86.     postfix.scan();
  87.     cout << postfix.postfix;
  88.  
  89.  
  90.     return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement