int Compute::cal(int n1, int n2, char c)
{
switch (c){
case '+': return n1 + n2;
case '-': return n1 - n2;
case '*': return n1 * n2;
case '/': return n1 / n2;
}
}
int Compute::compare_priory(char x, char y)
{
if (x == '*' || x == '/') return 1;
else if ((x == '+' || x == '-') && (y == '+' || y == '-')) return 1;
else return 0;
}
void Compute::to_postfix()
{
stack optr;
int len = infix.length();
int i;
for (i = 0; i < len; i++){
if (infix == ' ') {
continue;
} else if (isdigit(infix)){
if (i > 0 && (!isdigit(infix[i-1]))){
postfix.push_back(' ');
postfix.push_back(infix);
}else
postfix.push_back(infix);
} else {
if (optr.empty() || compare_priory(infix, optr.top())){
optr.push(infix);
}else {
while (!optr.empty() && compare_priory(optr.top(), infix)){
postfix.push_back(' ');
postfix.push_back(optr.top());
postfix.push_back(' ');
optr.pop();
}
optr.push(infix);
}
}
}
while (!optr.empty()){
postfix.push_back(' ');
postfix.push_back(optr.top());
postfix.push_back(' ');
optr.pop();
}
if (postfix.back() == ' ') postfix.pop_back();
}
int Compute::Cal()
{
int len = postfix.length();
if (len == 0) return 0;
stack s;
int i;
int nu = 0;
for (i = 0; i < len; i ++){
nu = 0;
if (postfix == ' ')
continue;
else if (isdigit(postfix)){
if (i > 0 && isdigit(postfix[i-1]) && !s.empty()){
nu = s.top();
nu = nu * 10 + postfix - '0';
s.pop();
s.push(nu);
}else
s.push(postfix - '0');
}else{
int n1 = s.top(); s.pop();
int n2 = s.top(); s.pop();
s.push(cal(n2, n1, postfix));
}
}
return s.top();
}