#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
#define MAXBUFFER 10
typedef double ElemType;
typedef struct{
Elemtype *base;
ElemType *top;
int stackSize;
}sqStack;
sqStack* InitStack(sqStack *s){ //注:最好在此使用sqStack*作为返回值,否则使用void无返回值可能存在内存溢出?
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if(!s->base)
exit(0);
s->top = s->base;
s->stackSize = STACK_NINT_SIZE;
return s;
}
Push(sqStack *s, ElemType e){
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->s->stackSzie;
s->stackSize = s->stackSize + STACKINREMENT;
}
*(s->top) = e;
s->top++;
}
Pop(sqStack *s, ElemType *e){
if(s->top == s->base)
return;
*e = *--(s->top);
}
int StackLen(sqStack s){
return (s.top - s.base);
}
int main(){ char c; double d,e; char str[MAXBUFFER]; int i=0; sqStack s; InitStack(&s); printf("请按逆波兰表达式输入待计算数据,数据与运算符之间用空格隔开,以#作为结束标志!\n"); scanf("%c",&c); while(c!= '#') { while(isdigit(c) || c=='.') //判断字符ASCII输入是否在48-57之间,对应0-9,用于过滤数字 { str[i++] = c; str[i] = '\0'; if(i >= 10) { printf("出错,输入的单个数据过大"); return -2; } scanf("%c",&c); //用于获取空格 if(' ' == c){ d = atof(str); Push(&s,d); //将d push进去 i = 0; break; } } switch (c) { case '+': Pop(&s,&e); //将栈顶数据pop出来,存到e Pop(&s,&d); //将栈顶数据pop出来,存到d Push(&s,d+e); break; case '-': Pop(&s,&e); Pop(&s,&d); Push(&s,d-e); //后者-前者 break; case '*': Pop(&s,&e); Pop(&s,&d); Push(&s,d*e); break; case '/': Pop(&s,&e); Pop(&s,&d); if(e != 0) Push(&s,d/e); else { printf("除数不为0"); return -1; } break; } scanf("%c",&c); //保证能够一直接受数据 } Pop(&s,&d); printf("最终的结果为: %f\n",d); return 0; }