#include <iostream>
#include <string>
using namespace std;
enum error_code1 {
success, overflow, underflow
};
template<class T>
class stack {
public:
stack();
bool empty()const;
bool full()const;
error_code1 get_top(T& x)const;
error_code1 push(const T x);
error_code1 pop();
private:
int count;
T data[100];
};
template <class T>
stack<T>::stack()
{
count = 0;
}
template <class T>
bool stack<T>::empty()const {
return count == 0;
}
template <class T>
bool stack<T>::full()const {
return count == 100;
}
template <class T>
error_code1 stack<T>::get_top(T& x)const {
if (empty()) return underflow;
x = data[count - 1];
return success;
}
template <class T>
error_code1 stack<T>::push(const T x) {
if (full()) return overflow;
data[count] = x;
count++;
return success;
}
template <class T>
error_code1 stack<T>::pop() {
if (empty()) return underflow;
count--;
return success;
}
template <class T>
bool ReferenceError(error_code1 a) {
if (a == overflow) {
cout << "overflow!" << endl;
return false;
}
if (a == underflow) {
cout << "underflow!" << endl;
return false;
}
return true;
}
//优先级
int Priority(char n) {
if (n == '+' || n == '-')
return 1;
else if (n == '*' || n == '/')
return 2;
else if (n == '(' || n == ')')
return 0;
else
return -1;
}
//四则运算
int calculate(char x, stack<int>& s) {
int a, b;
int c = 0;
s.get_top(b);
s.pop();
s.get_top(a);
s.pop();
switch (x) {
case '+': c = a + b;
break;
case '-': c = a - b;
break;
case '*': c = a * b;
break;
case '/': c = a / b;
break;
}
return c;
}
void calculator() {
stack<int> s1;
stack<char> s2;
string s;
cin >> s;
cout << "计算得:" << s;
s += '#';
s2.push('#');
for (int i = 0; i <= s.size(); i++) {
if (s[i] > '0' && s[i] < '9') {
int m = s[i] - 48;
while (s[i + 1] > '0' && s[i + 1] < '9') {
i++;
m = m * 10 + s[i] - 48;
}
s1.push(m);
}
else {
int k = 1;
char x, y;
s2.get_top(x);
while (k) {
if (Priority(s[i]) > Priority(x)) {
s2.push(s[i]);
break;
}
else if (s[i] == '(') {
s2.push(s[i]);
break;
}
else if (Priority(s[i]) == Priority(x) && Priority(s[i]) == 0) {
s2.pop();
break;
}
else if (Priority(s[i]) == Priority(x) && Priority(s[i]) == -1) {
s2.pop();
break;
}
else {
s1.push(calculate(x, s1));
s2.pop();
s2.get_top(y);
x = y;
}
}
}
}
int k;
s1.get_top(k);
cout << k << endl;
}
int main() {
calculator();
return 0;
}
栈结构独立