//顺序栈实现算术表达式的运算
//运算对象为整数
//建立顺序栈模板类
//主函数中调用教材计算表达式值的程序
// 读取
//计算时使用两个栈,一个存操作数,一个存运算符
//当栈外运算符优先级icp 高于栈顶运算符isp ,或操作数栈内没有两个数,运算符压入栈
//当栈顶运算符优先级icp 高于栈外运算符isp,栈顶运算符出栈,操作数出栈两个进行运算后压回栈顶
//仅支持0-9整数的算术表达式
#include<iostream>
using namespace std;
#include<string>
//建立顺序栈模板类
template <typename T>
class linestack {
public:
linestack(int maxsize);
~linestack();
bool isempty();//判空
bool isfull();//判满
T gettop();//返回栈顶值
int toptop() { return top; }//返回当前栈长
void push(T& x);//入栈
T pop();//出栈
private:
int top;//记录栈顶
int max;//记录栈大小
T* data;
};
template<typename T>
linestack<T>::linestack(int maxsize) {
max = maxsize;
data = new T[maxsize];
top = -1;
}
template<typename T>
linestack<T>::~linestack() {
delete[]data;
}
template<typename T>
bool linestack<T>::isempty() {
return top == -1;
}
template<typename T>
bool linestack<T>::isfull() {
return top == max - 1;
}
template<typename T>
T linestack<T>::gettop() {
return data[top];
}
//入栈
template<typename T>
void linestack<T>::push(T& x) {
if (isfull()) return;//栈满则无法插入
else data[++top] = x;
return;
}
//出栈
template<typename T>
T linestack<T>::pop() {
if (isempty()) return -1;//栈空无法出栈
else return data[top--];
}
//判断优先级
int icp(char ch) {
if (ch == '(') return 6;
else if (ch == '*' || ch == '/') return 4;
else if (ch == '+' || ch == '-') return 2;
else if (ch == ')') return 1;
}
int isp(char ch) {
if (ch == '(') return 1;
else if (ch == '*' || ch == '/') return 5;
else if (ch == '+' || ch == '-') return 3;
else if (ch == ')') return 6;
}
//取出两个操作数和一个运算符 结果再压入栈
void change(linestack<int>& sum, linestack<char>& cha) {
char ch = cha.pop();
if (ch == '(') return;
int a = sum.pop();
int b = sum.pop();
int c;
if (ch == '+') c = b + a;
else if (ch == '-') c = b - a;
else if (ch == '*') c = b * a;
else if (ch == '/') c = b / a;
sum.push(c);
return;
}
//主功能实现计算算术表达式
int main() {
string str;
while (cin >> str) {
linestack<int> num(20);
linestack<char> chr(20);
//一个栈存数 一个栈存运算符
for (int i = 0; i < str.size(); ++i){//string以\0结尾
if (str[i] <= '9' && str[i] >= '0') {//碰到数
int numb = str[i] - 48;
num.push(numb);
}else { //碰到操作符
if (!chr.isempty()) {//非空//不空时作判断
if (isp(chr.gettop()) >= icp(str[i]) ) {//退栈
change(num, chr);
}
}
if (str[i] != ')') chr.push(str[i]);//压入栈
}
}
while (num.toptop() > 0) change(num, chr);
cout << num.gettop() << endl;
}
return 0;
}
只实现到个位数整数的运算