標籤:linux c
棧:
中綴到尾碼的轉換。我們只允許操作+,*,(,)。
中綴運算式:a+b*c+(d*e+f)*g,尾碼運算式:abc*+de*f+g*+
程式如下,stack.h如上篇博文中所示:
#include<stdio.h>#include<string.h>#include<stdlib.h>#include"stack.h"char* infix_to_postfix(char* 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]==‘*‘){ while(!IsEmpty(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;}int main(){ char ss[]="a+b*c+(d*e+f)*g"; char* goal=infix_to_postfix(ss); printf("the string is :%s\n",goal); return 0;}
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/71/71/wKiom1XQOPjyKlL_AAD0NhTKcTY823.jpg" title="捕獲.JPG" alt="wKiom1XQOPjyKlL_AAD0NhTKcTY823.jpg" />
在上面的程式中的if(str[i]==‘+‘)語句後面加上如下兩個語句並修改相應的*對應的else if語句,就可以在運算式中使用+,-,*,、,(,)了。
else if(str[i]==‘-‘){ 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);}
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/71/72/wKiom1XQQBXBQPRwAADsBI3lPts135.jpg" title="捕獲.JPG" alt="wKiom1XQQBXBQPRwAADsBI3lPts135.jpg" />
《資料結構與演算法分析——c語言描述》讀後筆記 4