Skip to content

Instantly share code, notes, and snippets.

@WangZixuan
Last active September 7, 2018 09:07
Show Gist options
  • Save WangZixuan/be495397fec12b87bbe84a336f66153a to your computer and use it in GitHub Desktop.
Save WangZixuan/be495397fec12b87bbe84a336f66153a to your computer and use it in GitHub Desktop.
Postfix to Infix
#include <string>
#include <stack>
#include <iostream>
using namespace std;
bool isOperand(char x)
{
return (x >= 'a' && x <= 'z') ||
(x >= 'A' && x <= 'Z');
}
string getInfix(string exp)
{
stack<string> s;
stack<int> level;// */ is one, +- is 0, only character is -1
for (auto i = 0; exp[i] != '\0'; i++)
{
if (isOperand(exp[i]))
{
string op(1, exp[i]);
s.push(op);
level.push(-1);
}
else
{
auto op1 = s.top();
s.pop();
auto op2 = s.top();
s.pop();
auto l1 = level.top();
level.pop();
auto l2 = level.top();
level.pop();
/*
* Listed situations of l1 and l2:
* -1 0 1
* -1 1 4 3
* 0 4 1 2
* 1 3 2 1
*/
if (l1 == l2)//Situation 1
{
s.push(op2 + exp[i] + op1);
if (exp[i] == '*' || exp[i] == '/')
level.push(1);
else
level.push(0);
}
else if (l1 >= 0 && l2 >= 0)//Situation 2
{
if (exp[i] == '*' || exp[i] == '/')
{
if (l1 == 0)
s.push(op2 + exp[i] + "(" + op1 + ")");
else
s.push("(" + op2 + ")" + exp[i] + op1);
level.push(1);
}
else
{
s.push(op2 + exp[i] + op1);
level.push(0);
}
}
else if (l1 == 1 || l2 == 1)//Situation 3
{
s.push(op2 + exp[i] + op1);
if (exp[i] == '*' || exp[i] == '/')
level.push(1);
else
level.push(0);
}
else//Situation 4
{
if (exp[i] == '*' || exp[i] == '/')
{
if (l1 == -1)
s.push("(" + op2 + ")" + exp[i] + op1);
else
s.push(op2 + exp[i] + "(" + op1 + ")");
level.push(1);
}
else
{
s.push(op2 + exp[i] + op1);
level.push(0);
}
}
}
}
return s.top();
}
int main()
{
string exp = "ab+c*";
cout << getInfix(exp) << endl;
exp = "abc*+de*f+g*+";
cout << getInfix(exp) << endl;
exp = "ab+cde+**";
cout << getInfix(exp) << endl;
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment