Last active
February 15, 2018 10:15
-
-
Save whimo/9695e14cde377ee6827bb8a9de773e7e to your computer and use it in GitHub Desktop.
Reverse polish notation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <fstream> | |
| #include <string> | |
| #include <cmath> | |
| template <typename T> | |
| class Element | |
| { | |
| public: | |
| Element (T data): data (data), link (nullptr) {}; | |
| T data; | |
| Element* link; | |
| }; | |
| template <typename T> | |
| class Stack | |
| { | |
| public: | |
| Stack (): first (nullptr) {}; | |
| Element <T>* first; | |
| void push (T data) | |
| { | |
| Element <T>* new_first = new Element <T> (data); | |
| new_first -> link = first; | |
| first = new_first; | |
| } | |
| T pop () | |
| { | |
| T data = first -> data; | |
| Element <T>* tmp = first; | |
| first = first -> link; | |
| delete tmp; | |
| return data; | |
| } | |
| bool empty () { return (first == nullptr); } | |
| }; | |
| bool is_op (char data) { return (data == '+' || data == '-' || data == '*' || data == '/'); } | |
| bool priority (char op) { return (op == '*' || op == '/'); } | |
| int main () | |
| { | |
| Stack <char> stack; | |
| std::string expr; | |
| std::getline (std::cin, expr); | |
| std::string res = ""; | |
| for (size_t i = 0; i < expr.size(); i++) | |
| { | |
| if (std::isdigit (expr [i])) res += expr [i]; | |
| else if (expr [i] == '(') stack.push ('('); | |
| else if (expr [i] == ')') | |
| { | |
| char tmp = stack.pop (); | |
| while (is_op (tmp)) | |
| { | |
| res += tmp; | |
| tmp = stack.pop (); | |
| } | |
| } | |
| else if (is_op (expr [i])) | |
| { | |
| if (stack.empty ()) | |
| { | |
| stack.push (expr [i]); | |
| continue; | |
| } | |
| char tmp = stack.pop (); | |
| while (is_op(tmp) && priority (tmp) && !stack.empty()) | |
| { | |
| res += tmp; | |
| tmp = stack.pop (); | |
| } | |
| stack.push (tmp); | |
| stack.push (expr [i]); | |
| } | |
| } | |
| while (!stack.empty ()) | |
| res += stack.pop (); | |
| std::cout << res << std::endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment