#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define MAXSIZE 100
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct Stack {
ElemType* base;
int top;
int stacksize;
}Stack;
Status Initiate(Stack &S) {
S.base = (ElemType*)malloc(sizeof(ElemType) * MAXSIZE);
if (!S.base)return ERROR;
S.top = 0;//top指向栈顶的下一位
S.stacksize = MAXSIZE;
return OK;
}
Status Push(Stack &S, ElemType e) {
if (S.top == S.stacksize)return ERROR;
S.base[S.top] = e;
S.top++;
return OK;
}
int Pop(Stack &S, ElemType &e) {
if (S.top == 0){e=-1;return -1;}
S.top--;
e = S.base[S.top];
return e;
}
int main() {
int k, i,sign;//k个后缀式 sign为判断标志
ElemType t1, t2, res;//出栈的运算数
char ch[100];
i = 0;
int l, j;//字符串串长和第j+1位的字符
Stack s1;//运算数栈
Initiate(s1);
scanf("%d", &k);
if (k < 0 || k>10) {
printf("Expression Error!\n");
return 0;
}
else {
for (i = 0; i < k; i++) {//k个后缀式
scanf("%s", ch);
l = strlen(ch);
sign = 1;
char p;//
//1
//2222-/+
for (j = 0; j < l; j++) {//遇到数字入栈,遇到运算符则运算
if (ch[j] >='0' && ch[j] <= '9')//ch[j]是运算数
{
Push(s1, ch[j]-48);//入栈s1
}
else {//ch[j]是运算符
if (ch[j] == '+') {
Pop(s1, t2);
Pop(s1, t1);//若栈空返回-1
if(t2!=-1&&t1!=-1)
Push(s1, t1 + t2);//运算后入栈
else sign = -1;
}
if (ch[j] == '-') {
Pop(s1, t2);
Pop(s1, t1);
if(t2!=-1&&t1!=-1)
Push(s1, t1 - t2);
else sign = -1;
}
if (ch[j] == '*') {
Pop(s1, t2);
Pop(s1, t1);
if(t2!=-1&&t1!=-1)
Push(s1, t1 * t2);
else sign = -1;
}
if (ch[j] == '/') {
Pop(s1, t2);
Pop(s1, t1);
if (t2 == 0) {
sign = 0;//跳出
}
else{
if(t2!=-1&&t1!=-1)
Push(s1, t1 / t2);
else sign = -1;
}
}
if(sign==0||sign==-1)break;
}
}//0为除数跳出或完全遍历
if(sign==0){
printf("Division By Zero!\n");
}
if (s1.top==1&&ch[j]=='\0') {
Pop(s1, res);
printf("%d\n", res);
}
else if(s1.top!=1&&sign==1){
printf("Expression Error!\n");//栈不为空 有剩余运算数
}
else if(sign==-1){
printf("Expression Error!\n");//栈为空 有剩余运算符
}
}
}
return 0;
}