#include<stdio.h>
#include<stdlib.h>
#include <ctype.h>
#include"Stack.h"
Status InitStack(Stack* s) {
s->base = (SElemtype*)malloc(STACK_INIT_SIZE * sizeof(SElemtype));
if (!s->base) exit(OVERFLOW);
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
return 1;
}
//获取栈顶元素,并返回
Status GetTop(Stack s) {
SElemtype e;
if (s.top == s.base) return 0;
e = *(s.top - 1);
return e;
}
//插入元素e为新的栈顶元素
Status Push(Stack* s, SElemtype e) {
if (s->top - s->base >= s->stacksize)
{
s->base = (SElemtype*)realloc(s->base, (s->stacksize + STACKINCREASEMENT) * sizeof(SElemtype));
if (!s->base) exit(OVERFLOW);
s->top = s->base + s->stacksize;
s->stacksize += STACKINCREASEMENT;
}
*s->top++ = e;
return e;
}
//删除栈顶元素,并返回值
Status Pop(Stack* s)
{
SElemtype e;
if (s->top == s->base) {
printf("Empty Stack");
return 0;
}
e = *--s->top;
return e;
}
Status Judge(Status a1, Status a2, char c)
{
Status res = 0;
switch (c)
{
case '+':
res = a1 + a2;
break;
case '-':
res = a1 - a2;
break;
case '*':
res = a1 * a2;
break;
case '/':
if (a2 != 0)
res = a1 / a2;
else printf("wrong");
break;
}
return res;
}
void Evaluate(char* postfix) {
Stack s;
InitStack(&s); // 初始化栈
char* p = postfix;
while (*p != '\0') {
if (isdigit(*p)) { // 如果是数字
Status num = 0;
while (isdigit(*p)) { // 提取整数部分
num = num * 10 + (*p - '0');
p++;
}
Push(&s, num);
}
else if (*p == ' ') {
p++;
continue;
}
else if (isOperator(*p)) { // 如果是运算符
Status num2 = Pop(&s);
Status num1 = Pop(&s);
Status res = Judge(num1, num2, *p);
Push(&s, res);
p++;
continue;
}
}
printf("运算结果为:%d\n", GetTop(s));
}
int isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int main()
{
Stack num;
char in[200] ;
if (InitStack(&num)) printf("初始化成功\n");
scanf_s("%s", in,10); //指定缓冲区大小
Evaluate(in);
return 0;
}
它好像每次都输出表达式第一个值🥺