#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
//堆栈类
template <typename Type>
class Stack
{
private:
Type list[MAX_SIZE];
int top;//标记
public:
Stack();
void Push(const Type & a);//入栈
Type Pop();//出栈
void Clear();//清空栈
Type GetTop();//获取栈顶元素
bool IsEmpty()const;//判断堆栈是否为空
bool IsFull()const;//判断堆栈是否满
};
template<typename Type>
//堆栈初始化
Stack<Type>::Stack()
{
top =0;
}
template <typename Type>
//入栈
void Stack<Type>::Push(const Type &a)
{
if(top == MAX_SIZE)
return;
list[top++] = a;
}
//出栈
template <typename Type>
Type Stack<Type>::Pop()
{
return list[--top];
}
//清空堆栈
template <typename Type>
void Stack<Type>::Clear()
{
top =0;
}
//获取栈顶元素
template <typename Type>
Type Stack<Type>::GetTop()
{
int tp = top;
return list[--tp];
}
//判断栈是否空
template <typename Type>
bool Stack<Type>::IsEmpty()const
{
return top == 0;
}
//判断栈是否满
template <typename Type>
bool Stack<Type>::IsFull()const
{
return top == MAX_SIZE;
}
//判断优先权,返回优先级
char Precede(char op1,char op2)
{
char pre[7][7]={
{'>','>','<','<','<','>','>'},
{'>','>','<','<','<','>','>'},
{'>','>','>','>','<','>','>'},
{'>','>','>','>','<','>','>'},
{'<','<','<','<','<','=','>'},
{'>','>','>','>','>','>','>'},
{'<','<','<','<','<','>','='}
};
int x,y;
switch(op1)
{
case '+': x=0;
break;
case '-': x=1;
break;
case '*': x=2;
break;
case '/': x=3;
break;
case '(': x=4;
break;
case ')': x=5;
break;
case '=': x=6;
break;
}
switch(op2)
{
case '+': y=0;
break;
case '-': y=1;
break;
case '*': y=2;
break;
case '/': y=3;
break;
case '(': y=4;
break;
case ')': y=5;
break;
case '=': y=6;
break;
}
return pre[x][y];
}
//判断是否运算符
bool IsOPTR(char ch)
{
if(ch=='+'|| ch =='-'|| ch == '*'|| ch == '/'|| ch == '('|| ch == ')'|| ch == '=')
return true;
else
return false;
}
//计算函数
int Calculator(int a,char theta,int b)
{
switch(theta)
{
case '+':
return a+b;
break;
case '-':
return a-b;
break;
case '*':
return a*b;
break;
case '/':
return a/b;
break;
default:
return 0;
break;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Stack<char> optr;//运算符栈
Stack<int> opnd;//运算数栈
//opnd.Push(5);
//cout <<opnd.GetTop();
optr.Push('=');
char ch;
char out;
char theta;
int a,b,t=0;
cin >>ch;
while((ch!='=')||(optr.GetTop()!='='))
{
bool flag = false;
if(!IsOPTR(ch))//不是运算符则进运算数栈
{
while(!IsOPTR(ch))//可以是几位数
{
t = t*10+(ch-48);
cin >> ch;
}
opnd.Push(t);
t = 0;
}
else
{
switch(Precede(optr.GetTop(),ch))
{
case '<'://栈顶元素优先权低
optr.Push(ch);
cin >>ch;
break;
case '='://脱括号并接收下一个字符
out = optr.Pop();
cin >>ch;
break;
case '>'://退栈并将运算结果入栈
theta = optr.Pop();
b = opnd.Pop();
a = opnd.Pop();
opnd.Push(Calculator(a,theta,b));
break;
}
}
}
cout << opnd.GetTop() <<endl;
return 0;
}