栈应用之使用逆波兰输入求表达式的值

来源:互联网 发布:淘宝怎么买高仿包包 编辑:程序博客网 时间:2024/05/19 20:19
#include<stdio.h>#include<stdlib.h>#include<ctype.h>#define OK 1#define ERROR 0#define STACK_INIT_SIZE 20#define STACK_INCREMENT 10#define DIGITBUFFER 10typedef int    Status;typedef double Elemtype;typedef struct StackNode{Elemtype* base;Elemtype* top;int stackSize;}StackNode;typedef struct StackNode* Stack;Status InitStack(Stack s){s->base = (Elemtype*)malloc(sizeof(Elemtype) * STACK_INIT_SIZE);if(!s->base)return ERROR;s->top = s->base;s->stackSize = STACK_INIT_SIZE;return OK;}Status Pop(Stack s,Elemtype* result){if(s->base == s->top)return ERROR;*result = *(--s->top);return ERROR;}Status Push(Stack s,Elemtype value){if(s->top - s->base == s->stackSize){s->base = (Elemtype*)realloc(s->base,sizeof(Elemtype) * (STACK_INIT_SIZE + STACK_INCREMENT));if(!s->base)return ERROR;s->top = s->base + STACK_INIT_SIZE;s->stackSize = STACK_INIT_SIZE + STACK_INCREMENT;}*(s->top) = value;s->top++;return OK;}int StackLenth(Stack s){return s->top - s->base;}Status RPT(){//reverse polish notationchar c;double operater1,operater2;double result;int i = 0;char bufferDigit[DIGITBUFFER];Stack s;InitStack(s);printf("  Please Enter Reverse Polish Notation!(RPN)\n");printf("------note:  separated by space between -------\n");printf("------     number or operator.end of '#'-------\n");scanf("%c", &c);while(c != '#'){/* 处理输入的数字:由于使用%c接受输入,所以对于123这样的多位数的 * 输入%c是不能处理的。所以设置了char型的数组bufferDigit来缓存输 * 入的多位数。在开始了多位数的输入之后,必将以空格来结束该多位数 * 输入,所以if(c == ' ')用来判断多位数的结束。以便将缓存在char * 型数组中的多位数转化为double并且Push。 */while( isdigit(c) || c == '.'){if(i == 10){printf("number is too lager\n");return ERROR;}bufferDigit[i++] = c;bufferDigit[i] = '\0';scanf("%c", &c);if(c == ' '){//不是空格就一定还是数字result = atof(bufferDigit);Push(s,result);i = 0;}}/* 处理输入的运算符 */switch(c){case '+':Pop(s,&operater1);Pop(s,&operater2);Push(s,operater1 + operater2);break;case '-':Pop(s,&operater1);Pop(s,&operater2);Push(s,operater2 - operater1);break;case '*':Pop(s,&operater1);Pop(s,&operater2);Push(s,operater1 * operater2);break;case '/':Pop(s,&operater1);Pop(s,&operater2);Push(s,operater2 / operater1);break;}scanf("%c", &c);}Pop(s,&result);printf("The result of RPN is %f\n",result);}//test;Status ShowStack(Stack s){while(s->base != s->top){printf("%f ",*(--(s->top)));}printf("\n");}Status Test(){Stack s1;InitStack(s1);Push(s1,1);Push(s1,2);Push(s1,3);ShowStack(s1);}int main(){RPT();Stack s;InitStack(s);Push(s,1);Push(s,2);Push(s,3);ShowStack(s);return 0;}

0 0