(C语言算法)顺序栈实现整型算术表达式的求值
//author:邵俊平
#include <stdio.h>
#include <stack>
#include <iostream>
using namespace std;
stack<int> num;
stack<char> operate;
int opp(int x1, int x2, char c)
{
switch(c)
{case '+':
return x1 + x2;
case '-':
return x1 - x2;
case '*':
return x1 * x2;
case '/':
return x1 / x2;
}
}
int calculate(char *s)
{
char *p = s;
while(*p)
{
if(*p>='0' && *p<='9')
num.push(*p++ - '0');
else if(*p == ')')
{
int x1 = num.top();
num.pop();
int x2 = num.top();
num.pop();
char op = operate.top();
operate.pop();
operate.pop();
x1 = opp(x2, x1, op);
num.push(x1);
p++;
}
else if(*p == '*' || *p == '/')
{
char c = *p++;
int x2 = *p++ - '0';
// p++;
int x1 = num.top();
num.pop();
x1 = opp(x1, x2, c);
num.push(x1);
}
else if(*p == '+' || *p == '-' || *p == '(')
{
operate.push(*p++);
}
}
while(!operate.empty())
{
char c = operate.top();
operate.pop();
int x1 = num.top();
num.pop();
int x2 = num.top();
num.pop();
x1 = opp(x1, x2, c);
num.push(x1);
}
int x = num.top();
num.pop();
return x;
} <
#include <stdio.h>
#include <stack>
#include <iostream>
using namespace std;
stack<int> num;
stack<char> operate;
int opp(int x1, int x2, char c)
{
switch(c)
{case '+':
return x1 + x2;
case '-':
return x1 - x2;
case '*':
return x1 * x2;
case '/':
return x1 / x2;
}
}
int calculate(char *s)
{
char *p = s;
while(*p)
{
if(*p>='0' && *p<='9')
num.push(*p++ - '0');
else if(*p == ')')
{
int x1 = num.top();
num.pop();
int x2 = num.top();
num.pop();
char op = operate.top();
operate.pop();
operate.pop();
x1 = opp(x2, x1, op);
num.push(x1);
p++;
}
else if(*p == '*' || *p == '/')
{
char c = *p++;
int x2 = *p++ - '0';
// p++;
int x1 = num.top();
num.pop();
x1 = opp(x1, x2, c);
num.push(x1);
}
else if(*p == '+' || *p == '-' || *p == '(')
{
operate.push(*p++);
}
}
while(!operate.empty())
{
char c = operate.top();
operate.pop();
int x1 = num.top();
num.pop();
int x2 = num.top();
num.pop();
x1 = opp(x1, x2, c);
num.push(x1);
}
int x = num.top();
num.pop();
return x;
} <