#include
#include
#include
#include
using namespace std;
#define MAXSIZE 1000
typedef struct {
int in;
}IN;
typedef struct
{
IN* base;
IN* top;
int stacksize;
}SqStack;//构造栈元素
void InitStack(SqStack& s)//构造空栈s函数
{
s.base = (IN*)malloc(MAXSIZE * sizeof(IN));
s.top = s.base;
s.stacksize = MAXSIZE;
}
//入栈函数
void push(SqStack& s, int e) {
s.top->in = e;//将e压入栈顶
s.top++;//top上移
}
//出栈函数
int pop(SqStack& s) {
s.top--;
return s.top->in;
}
//获取栈顶元素
int Gettop(SqStack& s) {
return (s.top - 1)->in;
}
//计算函数
void ope(SqStack& A, SqStack& B) {
int a, b, s = 0;
char c;
a = pop(A);
b = pop(A);
c = pop(B);
switch (c) {
case '+':s = b + a; break;
case '-':s = b - a; break;
case '*':s = b * a; break;
case '/':s = b / a; break;
}
push(A, s);
}
//比较计算符优先级
char pre(char a, char b) {
if (b == '(')
return '0';//为(直接入栈
else {
if (a == '(') {
if (b == ')')
return '1';//左右括号相遇,左括号出栈
else
return '2';//左括号右侧第一个运算符入栈
}
else if (a == '*' || a == '/') {
if (b == ')')
return '3';//括号之间有尚未完成的运算符
else if (b == '*'|| b == '/')
return '=';
else
return '>';
}
else if (a == '+' || a == '-') {
if (b == '+'||b == '-')
return '=';
else if (b == ')')
return '3';
else
return '<';
}
}
}
int main()
{
SqStack num, sig;//构造两个栈,num:数字;;sig:运算符
InitStack(num);
InitStack(sig);
push(sig,'#'); //做栈底标记
char ch, c[10] = { '\0' };//ch存得到的字符,,c[50]将数字字符成串
int x=0,j=0; //x存储存c[50]转化的整形数字,j标记存c[50]
int t = 0;
ch = getchar();//读入第一个字符
for (; ch != '='; ch = getchar()) //用for循环进行输入,输入等号时结束,一次循环只处理一个字符
{
if ('0' <= ch && ch <= '9') {
c[j] = ch; //储存连续的数字字符
j++;
t = 1;
}
else {
if (t == 1) { //防止同时输入两个运算符使数与运算符匹配错位
c[j] = '\0';
x = atoi(c);
j = 0;
t = 0;
push(num, x);
}
int f = 0; //循环标记
while (f == 0) {
if (Gettop(sig) == '#') { //ch前无运算符,直接入栈
push(sig, ch);
break;
}
else {
switch (pre(Gettop(sig), ch)) {
case'0':push(sig, ch); f = 1; break;//ch位左括号,直接入栈
case '1':pop(sig); f = 1; break;//左右括号相遇,出括号,终止循环
case '2':push(sig, ch); f = 1; break;;//左括号右侧第一个运算符入栈
case '3':ope(num, sig); break;//括号之间有尚未完成的运算符
case '>':ope(num, sig); break;//若gettop(sig)之前有与ch同级运算符则继续比较,不终止比较循环
case '<':push(sig, ch); f = 1; break;
case '=':ope(num, sig); break;
}//switch
}//else
}//while
}//else
}//for
for (;;){ //完成=前剩余运算
ope(num, sig);
if (Gettop(sig) == '#') {
cout << pop(num);
break;
}
}
return 0;
}