数据结构表达式求值问题
程序代码:
#include<stdio.h> #include<stdlib.h> #include<malloc.h> #define STACK_INIT_SIZE 20 #define STACKINCREMENT 10 #define ERROR 0 #define OK 1 typedef int ElemType; typedef struct { ElemType *base; ElemType *top; int stacksize; }SqStack; int InitStack(SqStack *s) { s->base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType)); if(!s->base) return ERROR; s->top=s->base; s->stacksize=STACK_INIT_SIZE; return OK; } int Push(SqStack *s,char e) { if(s->top-s->base>=s->stacksize) { s->base=(ElemType *)realloc(s->base,(s->stacksize+STACKINCREMENT)*sizeof(ElemType)); if(!s->base) return ERROR; s->top=s->base+s->stacksize; s->stacksize+=STACKINCREMENT; } *(s->top)=e; s->top++; return OK; } int Pop(SqStack *s,char *e) { if(s->top==s->base) { return ERROR; } *e=*--(s->top); return OK; } char GetTop(SqStack s) { if(s.top==s.base) { return ERROR; } else { return (*(s.top-1)); } } int In(char c)//判断c是否为操作符 { switch(c) { case '+': case '-': case '*': case '/': case '(': case ')': case '#': return OK; break; default:return ERROR; } } char Priority(char t1,char t2) { char f; switch(t2) { case '+': case '-':if(t1=='('||t1=='#') f='<'; else f='>'; break; case '*': case '/':if(t1=='*'||t1=='/'||t1==')') f='>'; else f='<'; break; case '(':if(t1==')') return ERROR; else f='<'; break; case ')':switch(t1) { case '(':f='='; break; case '#':return ERROR;break; default:f='>'; } case '#':switch(t1) { case '#':f='=';break; case '(':return ERROR;break; default:f='>'; } } return f; } int operate(int a,char theta,int b) { int c; switch(theta) { case '+': c=a+b; break; case '-': c=a-b; break; case '*': c=a*b; break; case '/': c=a/b; break; } return c; } char final() { SqStack OPTR,OPND; char c,x,a,b; int i,j,e; InitStack(&OPTR); Push(&OPTR,'#'); InitStack(&OPND); printf("请输入表达式\n"); c=getchar(); while(c!='#'||GetTop(OPTR)!='#') { if(!In(c)) { Push(&OPND,c); c=getchar(); } else { switch(Priority(GetTop(OPTR),c)) { case '<':Push(&OPTR,c);c=getchar(); break; case '=':Pop(&OPTR,&x);c=getchar(); break; case '>':Pop(&OPTR,&x);Pop(&OPND,&a);Pop(&OPND,&b); i=atoi(&a);j=atoi(&b); e=operate(j,x,i); itoa(e,&a,10); Push(&OPND,a); break; } } } return (GetTop(OPND)); } int main() { char a; a=final(); printf("%c",a); printf("\n"); }
结果为什么不对啊?