Last active
November 18, 2019 04:25
-
-
Save paxbun/20659bd560dc4ce78c0cab3995123acc to your computer and use it in GitHub Desktop.
Infix to Postfix
This file contains 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 <string> | |
#include <unordered_map> | |
#include <utility> | |
#include <vector> | |
using namespace std; | |
unordered_map<char, unsigned> const prec = { | |
{ '^', 1 }, | |
{ '*', 2 }, | |
{ '/', 2 }, | |
{ '+', 3 }, | |
{ '-', 3 } | |
}; | |
string Parse(char const* str) | |
{ | |
vector<std::pair<char, unsigned>> stack; | |
string rtn; | |
while (*str) | |
{ | |
char c = *(str++); | |
if (auto it = prec.find(c); it != prec.end()) | |
{ | |
if (stack.empty() || stack.back().second > it->second) | |
stack.push_back(*it); | |
else | |
{ | |
while (!stack.empty() | |
&& stack.back().first != '(' | |
&& stack.back().second <= it->second) | |
{ | |
rtn.push_back(stack.back().first); | |
stack.pop_back(); | |
} | |
stack.push_back(*it); | |
} | |
} | |
else if (c == '(') | |
stack.push_back({ c, 0 }); | |
else if (c == ')') | |
{ | |
if (stack.empty()) | |
return "PARSE ERROR"; | |
while (stack.back().first != '(') | |
{ | |
rtn.push_back(stack.back().first); | |
stack.pop_back(); | |
} | |
stack.pop_back(); | |
} | |
else | |
rtn.push_back(c); | |
} | |
for (auto it = stack.rbegin(); it != stack.rend(); ++it) | |
rtn.push_back(it->first); | |
return rtn; | |
} | |
int main(int argc, char* argv[]) | |
{ | |
for (int i = 1; i < argc; ++i) | |
cout << Parse(argv[i]) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment