# include <stdio.h>
# include <stdlib.h>
# define M 1024
#define _CRT_SECURE_NO_WARNINGS
typedef int ElemType;
ElemType STACK[M];
int top;
int PUSH(int STACK[], int &top, int item);
int POP(int STACK[], int &top);
void printStack(int STACK[], int &top);
void INITIALS(int &top);
int Eval(char Express[]);
int main()
{
INITIALS(top);
char Express[50] = "1563/-2*+#";
printf("%s\n", Express);
int result = Eval(Express);
printf("计算结果;%d\n", result);
system("pause");
return 0;
}
void INITIALS(int &top)
{
top = -1;
}
int PUSH(int STACK[], int &top, int item)
{
if (top == M - 1)
{printf("stack is full!"); return 0;}
else
{
top = top + 1;
STACK[top] = item;
return 1;
}
}
int POP(int STACK[], int &top)
{
if (top == -1)
{ printf("stack is empty!"); return 0; }
else
{
int item = STACK[top];
top = top - 1;
return item;
}
}
void printStack(int STACK[], int &top)
{
for (int i=0; i<=top; i++)
{
printf("%d ", STACK[i]);
}
}
int Eval(char Express[])
{
int i = 0;
while (Express[i] != '#')
{
if (Express[i] > '0' && Express[i] < '9')
{
PUSH(STACK, top, Express[i] - 48); printf("读表达式,压栈%d\n", Express[i] - 48);
}
else if (Express[i] == '+')
{
printf("读到加号,当前栈中元素:");
printStack(STACK, top);
int T = POP(STACK, top) + POP(STACK, top);
PUSH(STACK, top, T);
printf("相加后压栈%d\n", T);
}
else if (Express[i] == '-')
{
printf("读到减号,当前栈中元素:");
printStack(STACK, top);
int a = POP(STACK, top);
int b = POP(STACK, top);
int T = b - a;
PUSH(STACK, top, T);
printf("相减后压栈%d\n", T);
}
else if (Express[i] == '*')
{
printf("读到乘号,当前栈中元素:");
printStack(STACK, top);
int T = POP(STACK, top) * POP(STACK, top);
PUSH(STACK, top, T);
printf("相乘后压栈%d\n", T);
}
else if (Express[i] == '/')
{
printf("读到除号,当前栈中元素:");
printStack(STACK, top);
int a = POP(STACK, top);
int b = POP(STACK, top);
int T = b / a;
PUSH(STACK, top, T);
printf("相除后压栈%d\n", T);
}
i++;
}
return POP(STACK, top);
}
效果
|