算数表达式转换:中缀转后缀,利用栈来实现

算数表达式转换:中缀转后缀,利用栈来实现

#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; 
}`
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值