/**************************************** 栈的一个应用表达式求值 写者:颜清国 06.3.20 ****************************************/ #include "stdio.h" #include "string.h" #define MAX 100 typedef struct sstack { char str[MAX]; int top; }stack; /*入栈操作*/ void push(stack *ta,char p) { ta->top++; ta->str[ta->top]=p; } /*出栈,返回栈顶的值*/ char pop(stack *ta) { char temp; if(ta->top==-1)/*栈已经空*/ { printf("stack is empty!"); return 0; } else { temp=ta->str[ta->top]; ta->top--; } return temp; } /*输出栈*/ void dispstack(stack ta) { int i=0; if(ta.top==-1)/*栈已经空*/ { printf("stack is empty!"); return; } printf("the stack elem are:"); for(;i< ta.top;i++) { printf("%c -----> ",ta.str[i]); } printf("%c",ta.str[ta.top]); } /****************************** 将中缀表达式转化为后缀表达式 *******************************/ void trans(char mid[],char last[]) { stack temp;/*临时栈,用来调整成后缀表达式*/ int lm=0,la=0,len=strlen(mid); temp.top=-1; /*初始栈为空*/ push(&temp,'(');/*整个表达式要加上括号*/ while(lm < len) { switch(mid[lm]) { case '-': /*'+''-'转化时,'('前的OP均出栈*/ case '+': /*注意必须先将整个表达式要加上括号*/ while(temp.str[temp.top]!='(') { last[la++]=pop(&temp); last[la++]='#'; /*加上'#'分隔符*/ } push(&temp,mid[lm]);/*自己入栈*/ break; case '*': case '/': while((temp.str[temp.top]=='*') ||(temp.str[temp.top]=='/')) { last[la++]=pop(&temp);/*栈顶是'*','/'则出栈*/ last[la++]='#'; /*加上'#'分隔符*/ } push(&temp,mid[lm]); /*自己入栈*/ break; case '(': push(&temp,'('); /*是'('直接入栈*/ break; case ')': while(temp.str[temp.top]!='(') { last[la++]=pop(&temp); /*将'('前所有OP出栈*/ last[la++]='#'; } pop(&temp); /*将'('出栈,自己不入栈*/ break; default: if((mid[lm] > '0')&&(mid[lm] <= '9'))/*可以屏蔽其它字符*/ { while((mid[lm] > '0')&&(mid[lm] <= '9')) { last[la++]=mid[lm++]; /*是数字保存到字串中*/ } last[la++]='#'; /*数字之间用分隔符隔开*/ lm--;/*需要退回来*/ } break; } lm++; /*依次扫描待转换的字串*/ } while(temp.top > 0) /*第0个元素为'(',不用保存*/ { last[la++]=pop(&temp); last[la++]='#'; } last[la]='/0'; /*标志后缀表达式结束*/ } int result(char str[]) { int temp[50],top=0,total=0; int i=0,len=strlen(str); while(i < len) { switch(str[i]) { case '+': temp[top-1]=temp[top-1] + temp[top]; /*相加*/ top--; /*下标减1*/ break; case '-': temp[top-1]=temp[top-1] - temp[top]; /*相加*/ top--; /*下标减1*/ break; case '*': temp[top-1]=temp[top-1] * temp[top]; /*相加*/ top--; /*下标减1*/ break; case '/': temp[top-1]=temp[top-1] / temp[top]; /*相加*/ top--; /*下标减1*/ break; default: total=0; while(str[i]!='#') { total=total*10 + str[i]-'0'; i++; } top++; temp[top]=total; i--; break; } i=i+2; /*去掉'#'号*/ } return temp[1]; } void main() { char str[100],str2[100]; printf("please in put the expression:"); gets(str); trans(str,str2); printf("/nthe result is %d:",result(str2)); getch(); }
栈的一个应用表达式求值
最新推荐文章于 2024-05-03 16:55:06 发布