标签:
栈实现逆波兰表达式
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("请按逆波兰表达式输入待计算数据,数据与运算符之间的空格隔开,以#作为结束标志:\n例如4 5 + #\n"); 59 scanf("%c",&c); 60 while(c != ‘#‘){ 61 while(isdigit(c) || c==‘.‘){ //判断字符是否为数字 ASCII是否为48-58之间 62 str[i++] = c; 63 str[i]=‘\0‘; 64 if(i >= 10){ 65 printf("输入的单个数据过大!请重新输入\n"); 66 } 67 scanf("%c",&c); 68 if(c == ‘ ‘){ 69 //单个数据输入结束,应该转换为dobule数据 70 d = atof(str); //将字符串转换为float型 数据 71 printf("入栈 %f\n",d); 72 push(&s,d); 73 i = 0; 74 break; 75 } 76 } 77 switch (c){ 78 case ‘+‘: 79 pop(&s,&e); 80 pop(&s,&d); 81 printf("+入栈 %f + %f = %f\n",d,e,d+e); 82 push(&s,d+e); 83 break; 84 case ‘-‘: 85 pop(&s,&e); 86 pop(&s,&d); 87 printf("-入栈 %f - %f = %f\n",d,e,d-e); 88 push(&s,d-e); 89 break; 90 case ‘*‘: 91 pop(&s,&e); 92 pop(&s,&d); 93 printf("*入栈 %f * %f = %f\n",d,e,d*e); 94 push(&s,d*e); 95 break; 96 case ‘/‘: 97 pop(&s,&e); 98 pop(&s,&d); 99 if(e != 0){ 100 printf("/入栈 %f / %f = %f\n",d,e,d/e); 101 push(&s,d/e); 102 }else{ 103 printf("\n除数不能为0!!!\n"); 104 return -1; 105 } 106 break; 107 } 108 scanf("%c",&c); 109 } 110 111 pop(&s,&d); //将最终的计算结果弹出 112 printf("\n计算结果为: %f\n",d); 113 return 0; 114 }
标签:
原文地址:http://www.cnblogs.com/lihaiyan/p/4394195.html