Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- */
- #include <cstdlib>
- #include <iostream>
- #include <string>
- #include<map>
- using namespace std;
- /*
- *
- */
- class post {
- private:
- string stack;
- string prefix;
- map<char, int> op;
- public:
- string postfix;
- post(string pre) : prefix(pre) {
- stack.clear();
- //Operator value table
- op['-'] = 1;
- op['+'] = 2;
- op['/'] = 3;
- op['*'] = 4;
- op['^'] = 5;
- op[')'] = -1;
- op['('] = -1;
- }
- void scan() {
- for (int i = 0; i < prefix.length(); i++) {
- if (isdigit(prefix[i])) {
- postfix += prefix[i];
- } else if(prefix[i] != ' ') {
- checkStack(prefix[i]);
- }
- }
- for (int i = stack.length(); i >= 0; i--) {
- if (op[stack[i]] != -1)
- postfix += stack[i];
- }
- }
- void checkStack(char sym) {
- int i = stack.length() - 1;
- int newsym = op[sym];
- cout << stack << endl;
- if (stack.empty()) {
- stack += sym;
- return;
- } else {
- if (newsym > op[stack[i]]) {
- stack += sym; //push
- return;
- } else {
- while (newsym <= op[stack[i]]) {
- if (op[stack[i]] != -1)
- postfix += stack[i]; //pop in to the postfix expression
- stack.erase(stack.end() - 1); //pop out the stack
- i--;
- if (stack.empty())
- break;
- }
- stack += sym; //push
- }
- }
- }
- };
- int main(int argc, char** argv) {
- string prefix = "(5+3)*12/3";
- post postfix(prefix);
- postfix.scan();
- cout << postfix.postfix;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement