Skip to content

Instantly share code, notes, and snippets.

@paxbun
Last active November 18, 2019 04:25
Show Gist options
  • Save paxbun/20659bd560dc4ce78c0cab3995123acc to your computer and use it in GitHub Desktop.
Save paxbun/20659bd560dc4ce78c0cab3995123acc to your computer and use it in GitHub Desktop.
Infix to Postfix
#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