- 论坛徽章:
- 0
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define add 43
#define subs 45
#define mult 42
#define div 47
#define MAXSIZE 100
typedef struct {
int stkdata[MAXSIZE];
int top ;
}STKzone;
typedef STKzone *STK;
typedef enum{true=1,false=0} bool;
typedef enum{ok,error} status;
STKzone expSTKzone;
STK expSTK;
/*执行栈的初始化,建栈指针*/
STK initSTK(STKzone *stack_zone) {
STK p;
p = stack_zone;
p->top=0;
}
/*将一些结构型数据送入栈中*/
status push(int *term,STK pstk) {
if(pstk->top == MAXSIZE) {
return error;
}
pstk->stkdata[pstk->top] = *term;
(pstk->top)++;/*栈顶指针移动 */
return ok;
}
/*判定栈是否为空*/
bool emptySTK(STK pstk) {
return (pstk->top == 0);
}
/*从栈内出来一些数据结构 */
status pop(int *pdata, STK pstk) {
if(emptySTK(pstk))
return error;
(pstk->top)--;
*pdata = pstk->stkdata[pstk->top];
return ok;
}
void synerror(void) {
printf("n表达式语法错误");
exit(1);
}
int eval (char tag,int a1,int a2) {
switch(tag) {
case add:return (a1+a2);
case subs:return (a1-a2);
case mult: return (a1*a2);
case div: return (a1/a2);
}
}
int main() {
char c;
int opd1,opd2,temp,c1;
expSTK = initSTK(&expSTKzone);
printf("n后置表达式");
while((c=getchar())!= 'n') {
if(c==' ') continue ;
if((c>47)&&(c<58)) {
putchar(c);
c1=c-48;
if(push(&c1,expSTK)==error){/*运算夫进栈*/
printf("n表达式太长n");
exit(0);
}
}else if((c == add) || (c == subs) || (c==mult)||(c==div)){
putchar(c);
if(pop(&opd1,expSTK) == error) synerror();
if(pop(&opd2,expSTK) == error) synerror();
temp = eval(c,opd2,opd1);
push(&temp,expSTK);
}else synerror();
}
if((pop(&opd1,expSTK)==error)) synerror();
if(!(emptySTK(expSTK))) synerror();
printf("=%-3dn",opd1);
谢谢,哪里错了?
} |
|
|