算数表达式转换:中缀转后缀,利用栈来实现
#include <stdio.h>
#include <stdlib.h>
#define max 50
int push(char *a,int top,char elem);
int pop(char *a,int top);
int main(int argc, char *argv[]) {
int top=0;
char a[max],//存放结果序列
b[max],//存放原序列
c[max];//存放栈
char s=NULL;
int i=0;
while(s!='#'){ //输入栈元素 以#号结束
scanf("%c\n",&s);
b[i++]=s;
}
int j,m=0;
for(j=0;j<i;j++){
if(b[j]=='('){ //若为左括号则直接入栈;
top=push(c,top,b[j]);
}else if((b[j]>64&&b[j]<91)||(b[j]>96&&b[j]<123)){
a[m++]=b[j];
}else if(b[j]=='+'||b[j]=='-'||b[j]=='*'||b[j]=='/'){ //若为“+”,“-”,“*”,“/”,需要进行讨论;
if(top==-1){ //栈空,入栈;
top=push(c,top,b[j]);
}else if(c[top]=='('){ //栈顶元素为“(”,入栈;
top=push(c,top,b[j]);
}
}else if(b[j]==')'){ //若为右括号则依次把栈中的运算符加入后缀表达式,直到出现"(",并从栈中将“(”出栈;
while(c[top]!='('){
a[m++]=c[top];
top=pop(c,top);
}
top=pop(c,top);
}
}
printf("%d\n",m);
for(j=0;j<m;j++){
printf("%c\n",a[j]);
}
return 0;
}
int push(char *a,int top,char elem){ //入栈操作;
if(top==max-1){
printf("栈满");
return -1;
}
a[++top]=elem;
printf("%c:入栈,top=%d\n",elem,top);
return top;
}
int pop(char *a,int top){ //出栈操作;
if(top==-1){
printf("空栈");
return -1;
}
top--;
printf("弹出:%c,top=%d\n",a[top],top);
return top;
}`