栈实现逆波兰表达式
2015-04-05 Lover雪儿
1 //逆波兰表达式 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <math.h> 5 #include <ctype.h> 6 7 #define STACK_INIT_SIZE 20 //初始栈大小 8 #define STACK_INCREMENT 10 //扩充栈时每次增加的内存 9 #define MAXBUFFER 10 //缓冲区 10 11 typedef double ElemType; //栈中的数据类型 12 typedef struct { 13 ElemType *base; 14 ElemType *top; 15 int stackSize; 16 }sqStack; 17 18 //初始化栈 19 void init_stack(sqStack *s){ 20 s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType)); 21 if(!s->base) 22 exit(-1); 23 s->top = s->base; 24 s->stackSize = STACK_INIT_SIZE; 25 } 26 //入栈 27 void push(sqStack *s,ElemType e){ 28 if(s->top - s->base >= s->stackSize){ //检测栈是否已满 29 //若是已满,则自动扩大栈空间 30 s->base = (ElemType *)realloc(s->base, (s->stackSize + STACK_INCREMENT)*sizeof(ElemType)); 31 if(!s->base) 32 exit(-1); 33 } 34 *(s->top) = e; 35 s->top++; 36 } 37 //出栈 38 void pop(sqStack *s, ElemType *e){ 39 if(s->top == s->base){ 40 return ; 41 } 42 *e = *(--(s->top)); 43 } 44 //求栈数据的个数,由于我们不会对其修改,故此处不需传指针 45 int stack_len(sqStack s){ 46 return (s.top - s.base); //返回数据的个数 47 } 48 49 int main(void){ 50 sqStack s; 51 char c; 52 double d,e; 53 char str[MAXBUFFER]; 54 int i = 0; 55 56 init_stack(&s); 57 58 printf("请按逆波兰表达式输入待计算数据,数据与运算符之间的空格隔开,以#作为结束标志: 例如4 5 + # "); 59 scanf("%c",&c); 60 while(c != '#'){ 61 while(isdigit(c) || c=='.'){ //判断字符是否为数字 ASCII是否为48-58之间 62 str[i++] = c; 63 str[i]='