到目前为止,我刚刚完成表达式转换为后缀表达式,我尝试评估但出现问题并让我很长时间感到困惑,我只知道如何修复它。
这是我的代码转向后缀表达式:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
#define MAXBUFFER 10
#define OK 1
#define ERROR 0
typedef char ElemType;
typedef int Status;
typedef struct {
ElemType *base;
ElemType *top;
int stackSize;
}sqStack;
Status InitStack(sqStack *s) {
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if ( !s->base ) {
exit(0);
}
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
return OK;
}
Status Push(sqStack *s, ElemType e) {
//if the stack is full
if ( s->top - s->base >= s->stackSize ) {
s->base = (ElemType *)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
if ( !s->base ) {
exit(0);
}
s->top = s->base + s->stackSize;
s->stackSize += STACKINCREMENT;
}
//store data
*(s->top) = e;
s->top++;
return OK;
}
Status Pop(sqStack *s, ElemType *e) {
if ( s->top == s->base ) {
return ERROR;
}
*e = *--(s->top);
return OK;
}
int StackLen(sqStack s) {
return (s.top - s.base);
}
int main() {
sqStack s;
char c;
char e;
InitStack(&s);
printf("Please input your calculate expression(# to quit):\n");
scanf("%c", &c);
while ( c != '#' ) {
while ( c >= '0' && c <= '9' ) {
printf("%c", c);
scanf("%c", &c);
if ( c < '0' || c > '9' ) {
printf(" ");
}
}
if ( ')' == c ) {
Pop(&s, &e);
while ( '(' != e ) {
printf("%c ", e);
Pop(&s, &e);
}
} else if ( '+' == c || '-' == c ) {
if ( !StackLen(s) ) {
Push(&s, c);
} else {
do {
Pop(&s, &e);
if ( '(' == e ) {
Push(&s, e);
} else {
printf("%c", e);
}
}while ( StackLen(s) && '(' != e );
Push(&s, c);
}
} else if ( '*' == c || '/' == c || '(' == c ) {
Push(&s, c);
} else if ( '#' == c ) {
break;
} else {
printf("\nInput format error!\n");
return -1;
}
scanf("%c", &c);
}
while ( StackLen(s) ) {
Pop(&s, &e);
printf("%c ", e);
}
return 0;
}
当我输入 3*(7-2)# 它返回 3 7 2 -
事情进展顺利,但我不知道接下来如何评估它,我只是将它转换为后缀表达式,我想使用堆栈来评估它。