使用栈计算中缀表达式

这里只能用于计算十以内的表达式

/**
 *
 *	作者: LinX  2017-6-18 - 2017-6-19
 *
 *
 *  内容: 运用栈对中缀表达式求值
 * 
 */ 
 
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
 #define MAXSIZE 100
 
 char oper[MAXSIZE];  	 		 //操作符栈 
 int topOper=-1;		 		 //栈顶指针 
 	
 int nums[MAXSIZE];	 	 		 //数字栈 
 int topNums=-1;		 		 //栈顶指针 
 
 int MedExp(char *exp,int *res);   		 //计算表达式值
 
 int countStackTopTwo();		 		//计算两个栈顶元素相加 
 
 int count(char op,int num1,int num2,int *result);		//计算每一步两个数相加 
 
 int judgePrior(char op);								//比较符号的优先级 
 
 int main()
 {
 	int res;
 	
	char exp[MAXSIZE];
	
  	printf("输入表达式: ");
  	
  	gets(exp);
  	
  	if(MedExp(exp,&res)==0)
  	{
  		printf("表达式错误!\n");
  		return 0;
  	}
  	
  	printf("%d\n",res);
  	
  	return 0;
  	
 }
 
 int countStackTopTwo()
 {
 	int result;
 				
 	char op=oper[topOper--];
 				
 	int num1=nums[topNums--];
 				
 	int num2=nums[topNums--];			
 				
 	if(count(op,num2,num1,&result)==0)
 	{	
 		//printf();
 		return 0;
 	}
 	nums[++topNums]=result;
 	//printf("res=%d\n",result);
	return 1;		
 }
 
 int MedExp(char *exp,int *res)
 {
 	int i=0,flag,j=0;
 	while(exp[i]!='\0')
 	{

 		if('0'<=exp[i]&&exp[i]<='9')
 		{
 			
 			nums[++topNums]=exp[i]-'0';
 			
 		}
 		
 		else if(exp[i]=='(')
 		{
 			
 			oper[++topOper]=exp[i];
 			
 		}
 		
 		else if(topOper==-1)
 		{
 			
 			oper[++topOper]=exp[i];
 			
 		}
 		
 		else if(exp[i]=='+'||
		 		  exp[i]=='-'||
				    exp[i]=='*'||
				      exp[i]=='/')
 		{
 			
 			if(oper[topOper]=='('||judgePrior(exp[i])>judgePrior(oper[topOper]))
 			{
 				
 				oper[++topOper]=exp[i];
 				
 			}
 			
 			else
 			{
 				
 				flag=countStackTopTwo();
 				
 				if(flag==0)
 				{
 					
 					return 0;
 					
 				}
 				
				oper[++topOper]=exp[i]; 		
 			}
 		}
 		
 		else if(exp[i]==')')
 		{
 			
 			while(oper[topOper]!='(')
 			{
 				
 				flag=countStackTopTwo();
 				
 				if(flag==0)
 				{
 					return 0;
 				}
 			}
 			
 			topOper--;
 		}
 		
 		i++;
 		
	}
	while(topOper!=-1)
	{
		
		flag=countStackTopTwo();
		
 		if(flag==0)
 		{
 			return 0;
 		}
	} 
	
	*res=nums[topNums];
		
	return 1;
 }
 			
 int count(char op,int num1,int num2,int *result)
 {
 	if(op=='+')
 	{
 		*result=num1+num2;
 	}
 				
 	else if(op=='-')
 	{
 		*result=num1-num2;
 	}
 			
 	else if(op=='*')
 	{
 		*result=num1*num2;
 	}
 				
 	else if(op=='/')
 	{
 		if(num2==0)
 		{
 			return 0;
 		}
 		*result=num1/num2;
 	}
 	return 1;
 } 
 
 int judgePrior(char op)
 {
 	 if(op=='+'||op=='-')
	 {
	 	return 0;
	 } 
	 return 1;
 }
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值