#include <stdio.h>
#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef struct LNode
{
int OPNT[MAXSIZE];
int top1;
} LNode; //操作数栈
typedef struct SLNode
{
char OPRT[MAXSIZE];
int top2;
} SLNode; //运算符栈;
void Init_Stack1(LNode &Q)
{
Q.top1 = 0;//栈顶指针永远指向栈顶元素的上一个
}
void Init_Stack2(SLNode &S)
{
S.top2 = 0;
}
bool Push_stack1(LNode &Q, int &x)
{
if (Q.top1 < MAXSIZE)
{
Q.OPNT[Q.top1] = x;
Q.top1++;
return true;
}
else
{
return false;
}
}
bool Push_stack2(SLNode &S, char &x)
{
if (S.top2 < MAXSIZE)
{
S.OPRT[S.top2] = x;
S.top2++;
return true;
}
else
{
return false;
}
}
bool Get_head1(LNode &Q, int &x)
{
if (0 < Q.top1 && Q.top1 < MAXSIZE)
{
x = Q.OPNT[Q.top1 - 1];
return true;
}
else
{
return false;
}
}
bool Get_head2(SLNode &S, char &x)
{
if (0 < S.top2 && S.top2 < MAXSIZE)
{
x = S.OPRT[S.top2 - 1];
return true;
}
else
{
return false;
}
}
bool Pop_stack1(LNode &Q, int &x)
{
if (Q.top1 != 0)
{
Q.top1--;
x = Q.OPNT[Q.top1];
return true;
}
else
{
return false;
}
}
bool Pop_stack2(SLNode &S, char &x)
{
if (S.top2 != 0)
{
S.top2--;
x = S.OPRT[S.top2];
return true;
}
else
{
return false;
}
}
bool Priority(char a, char b)
{
//用于判断运算符优先级的高低,优先级高于或等于就返回true,否则为false
if ((a == '+' || a == '-') && (b == '+' || b == '-' || b == '*' || b == '/'))
{
return true; //尽管后一个与前一个一个相同但还是后一个优先级高
}
else if ((a == '*' || a == '/') && (b == '*' || b == '/'))
{
return true;
}
else
{
return false;
}
}
int CalculateTwo(int n1, int n2, char x)
{
if (x == '+')
{
return n1 + n2;
}
if (x == '-')
{
return n2 - n1;
}
if (x == '*')
{
return n1 * n2;
}
if (x == '/')
{
return n2 / n1;
}
}
void Calculate(char str[], int &e)
{
LNode Q;
SLNode S;
Init_Stack1(Q);
Init_Stack2(S);
int i, n1, n2, n = 0, sum; //用来算存进OPNT栈中的数;
char t; //存一个操作符;
for (i = 0; str[i] != '#'; i++)
{
if ('0' <= str[i] && str[i] <= '9')
{
//n = 0;
while (1)
{
n = n * 10;
n += (str[i] - '0');
if ('0' <= str[i + 1] && str[i + 1] <= '9')
{
i++;
}
else
break;
}
Push_stack1(Q, n);
n = 0;
}
else if (str[i] != ')')
{
while (Get_head2(S, t) && t != '(' && Priority(str[i], t))
{
Pop_stack2(S, t); //后来的比原来的优先级低就弹出后再放回;
Pop_stack1(Q, n1);
Pop_stack1(Q, n2);
sum = CalculateTwo(n1, n2, t);
Push_stack1(Q, sum);
}
Push_stack2(S, str[i]);
}
else
{
while (Pop_stack2(S, t))
{
if (t == '(')
{
break;
}
else
{
Pop_stack1(Q, n1);
Pop_stack1(Q, n2);
sum = CalculateTwo(n1, n2, t);
Push_stack1(Q, sum);
}
}
}
}
while (Pop_stack2(S, t) && Pop_stack1(Q, n1) && Pop_stack1(Q, n2))
{
sum = CalculateTwo(n1, n2, t);//栈中还有元素的把栈中元素用完
Push_stack1(Q, sum);
}
Pop_stack1(Q, e);
}
int main()
{
char str[MAXSIZE];
int e;
cin >> str;
// push
//cout<<str;
LNode Q;
SLNode S;
int x;
char y;
Init_Stack1(Q);
Init_Stack2(S);
//Push_stack1(Q,x);
// Pop_stack1(Q,x);
// cout<<x<<endl;
// Push_stack2(S,'+');
// Pop_stack2(S,y);
// cout<<y<<endl;
Calculate(str, e);
cout << e << endl;
}
等以后学会了STL在来补STL的算法