Converts an infix expression to a suffix expression and outputs, and then computes the value of the suffix expression.
Program:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "stack.h" char* infix_to_ Postfix (CHAR*&NBSP;STR) { int i,j=0; int size=strlen ( STR); if (str==null) {printf ("Empty string!!! \ n "); Return null; } stack s=createstack (SIZE); char *tmpstr=malloc (sizeof (char) * (size+1)); if (Tmpstr==null) {printf ("tmpstr is empty!\n"); return null; } for (i=0;i<size;++i) {if (str[i]== ' + ') { while (! IsEmpty (s) && top (s)! = ' (' ) {tmpstr[j++]=topandpop (s); } push (' + ', s); }else if (str[i]== '-') {&NBSP;&NBSP;&NBSp; while (! IsEmpty (s) && top (s)! = ' (' ) { tmpstr[j++]=topandpop (s); } push ('-', s);} Else if (str[i]== ' * ') { while (! IsEmpty (s) && (Top (s) = = ' * ' | | top (s) = = '/') ) {tmpstr[j++]=topandpop (s); } push (' * ', s);} Else if (str[i]== '/') { while (! IsEmpty (s) && (Top (s) = = ' * ' | | top (s) = = '/') ) {tmpstr[j++]=topandpop (s); } push ('/', s);} else if (str[i]== ' (') { push (str[i],s);} else if (str[i]== ') ' { while (Top (s)! = ' (') { Tmpstr[j++]=topandpop (s); } pop (s);} else{ tmpstr[j++]=Str[i];} } while (! IsEmpty (s)) {tmpstr[j++]=topandpop (s); } Return tmpstr;} Void compute (char *goal) { int i,pre,next,sum; Stack s=createstack (strlen (goal)); if (S==null) return ; push (goal[0],s); push (goal[1],s); for (I=2;i<strlen (goal ); ++i) {switch (goal[i]) { case ' * ': { Pre=topandpop (s); Next=topandpop (s); sum= (pre-' 0 ') * (next-' 0 '); Push ((char) (sum+ ' 0 '), s);break; } case '/': {pre=topandpop (s); Next=topandpop (s); sum= (next-' 0 ')/(pre-' 0 '); Push ((char) (sum+ ' 0 '), s);break; } case ' + ': {pre=topandpop (s); nExt=topandpop (s); sum= (next-' 0 ') + (pre-' 0 '); Push (char) (sum+ ' 0 '), s);break; } case '-': {pre=topandpop (s); Next=topandpop (s); sum= (next-' 0 ')-(pre-' 0 '); Push ((char) (sum+ ' 0 '), s);break; } default: {push (goal[i],s);break; } } } printf ("the result is : %d\n", (Top (s)-' 0 '));} Int main () { char ss[]= "1+2*3+ (4*1+6)"; char* goal =infix_to_postfix (ss); printf ("the string is :%s\n", goal); compute (goal); return 0;}
650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/71/6F/wKioL1XQVPTBfyo8AAEYimrPgEo234.jpg "title=" capture. JPG "alt=" Wkiol1xqvptbfyo8aaeyimrpgeo234.jpg "/>
One drawback of the above program is that only the calculation of the size of sizeof (char) can be obtained, such as a char of 1 bytes, then the expression can only be evaluated with a maximum of 256. The reason is that the array in the stack used in the compute () function is of type char. If the Infix_to_postfix () function is separated from the compute () function and written in a different. c file, so that the stack they call is of type char and int, then an arbitrary range of expressions can be computed.
"Data structure and algorithm analysis--c language description" after reading Note 5