测试用例:
9 3 1-3*+ 8 2/+
#include <iostream>
#include<math.h>
using namespace std;
#define InitSize 100
#define StackIncrement 50
typedef int ElemType;
typedef struct { //顺序栈定义
ElemType* elem; //栈数组
int top; //或ElemType*,栈顶指针
int size; //栈大小
} SeqStack;
int InitStack(SeqStack& S) { //初始化
S.elem = new ElemType[InitSize];
if (!S.elem) exit(1);
S.top = -1;
S.size = InitSize;
return 1;
}
int IsEmpty(const SeqStack& S) {
//判断栈是否空,空则返回1,否则返回0
return S.top == -1;
}
int IsFull(const SeqStack& S) {
//判断栈是否,满则返回1,否则返回0
return S.top == S.size;
}
int Push(SeqStack& S, ElemType &e) {
//若栈满返回0, 否则新元素 e 进栈并返回1
if (IsFull(S)) return 0;
S.top++; //先移动指针
S.elem[S.top] = e; //再加入新元素
return 1;
}
int Pop(SeqStack& S, ElemType &e) {
//若栈空返回0, 否则栈顶元素退出到e并返回1
if (IsEmpty(S)) return 0;
e = S.elem[S.top]; S.top--;
return 1;
}
int GetTop(const SeqStack& S, ElemType& e) {
//若栈空返回0, 否则栈顶元素读到e并返回1
if (IsEmpty(S)) return 0;
e = S.elem[S.top];
return 1;
}
void Traverse(const SeqStack& S) {//遍历栈
if (IsEmpty(S)) cout << "空表,无法遍历" << endl;
for (int i = 0; i <= S.top; i++) {
cout << S.elem[i] << endl;
}
}
int IsOp(char c) {
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^')
return 1;
else {
return 0;
}
}
int Compute(char c, int a, int b) {
if (c == '+')return a + b;
else if (c == '-')return a - b;
else if (c == '*')return a * b;
else if (c == '/')return a / b;
else if (c == '^')return pow(a, b);
else return 0;
}
void CalculateSuffix(SeqStack& S) {
char c; int rst=0; int e;
while ((c = getchar()) != '\n') {
int x1 = 0; int x2 = 0;
if (!IsOp(c)) {
int a = c - '0';
Push(S, a);
}//char转为int入栈
else { //c为操作符
Pop(S, x2); Pop(S, x1);
rst = Compute(c, x1, x2);//计算x1 c x2
Push(S, rst);
}
}
GetTop(S, e);
cout << endl<<"该表达式的值为:"<<e;
}
int main() {
SeqStack S;
InitStack(S);
//931-3*+82/+
CalculateSuffix(S);
}