Stack implementation Inverse Polish expression
2015-04-05 Lover Snow Child
1 //Inverse Polish expression2#include <stdio.h>3#include <stdlib.h>4#include <math.h>5#include <ctype.h>6 7 #defineStack_init_size 20//Initial Stack size8 #defineStack_increment 10//increased memory each time the stack is expanded9 #defineMaxbuffer 10//buffersTen OnetypedefDoubleElemtype;//data types in the stack Atypedefstruct { -Elemtype *Base; -Elemtype *top; the intstackSize; - }sqstack; - - //Initialize Stack + voidInit_stack (Sqstack *s) { -S->Base= (Elemtype *)malloc(Stack_init_size *sizeof(Elemtype)); + if(!s->Base) AExit (-1); atS->top = s->Base; -S->stacksize =stack_init_size; - } - //into the stack - voidPush (Sqstack *S,elemtype e) { - if(s->top-s->Base>= s->stacksize) {//detects if the stack is full in //if full, the stack space is automatically expanded -S->Base= (Elemtype *)realloc(s->Base, (s->stacksize + stack_increment) *sizeof(Elemtype)); to if(!s->Base) +Exit (-1); - } the* (s->top) =e; *s->top++; $ }Panax Notoginseng //out of the stack - voidPop (Sqstack *s, Elemtype *e) { the if(S->top = = s->Base){ + return ; A } the*e = * (--(s->top)); + } - //the number of stack data, because we do not modify it, so there is no need to pass pointers $ intStack_len (Sqstack s) { $ return(S.top-s.Base);//number of returned data - } - the intMainvoid){ - Sqstack S;Wuyi CharC; the Doubled,e; - CharStr[maxbuffer]; Wu inti =0; - AboutInit_stack (&s); $ -printf"press the inverse Polish expression to enter the data to be calculated, separated by a space between the data and the operator, with # as the closing flag: \ n For example 4 5 + #\n"); -scanf"%c",&c); - while(c! ='#'){ A while(IsDigit (c) | | | c=='.'){//determines whether a character is a numeric ASCII 48-58 or not +str[i++] =C; thestr[i]=' /'; - if(I >=Ten){ $printf"The single data entered is too large! Please re-enter \ n"); the } thescanf"%c",&c); the if(c = =' '){ the //Single data entry ends and should be converted to Dobule data -d = atof (str);//Convert a string to float type data inprintf"into the stack%f\n", d); thePush (&s,d); thei =0; About Break; the } the } the Switch(c) { + Case '+': -Pop (&s,&e); thePop (&s,&d);Bayiprintf"+ into the stack%f +%f =%f\n", d,e,d+e); thePush (&s,d+e); the Break; - Case '-': -Pop (&s,&e); thePop (&s,&d); theprintf"-Into the stack%f-%f =%f\n", d,e,d-e); thePush (&s,d-e); the Break; - Case '*': thePop (&s,&e); thePop (&s,&d); theprintf"* into the stack%f *%f =%f\n", d,e,d*e);94Push (&s,d*e); the Break; the Case '/': thePop (&s,&e);98Pop (&s,&d); About if(E! =0){ -printf"/into the stack%f/%f =%f\n", d,e,d/e);101Push (&s,d/e);102}Else{103printf"\ n The divisor cannot be 0!!! \ n");104 return-1; the }106 Break;107 }108scanf"%c",&c);109 } the 111Pop (&s,&d);//The final result of the calculation is popped theprintf"\ n evaluates to:%f\n", d);113 return 0; the}
Stack implementation Inverse Polish expression