栈实现中缀表达式的值

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <stack>
#include <cstring>
using namespace std;
int youXianJi(char a){      //字符判断优先级 
	int k;   
	switch(a){
		case'+': case'-':  k = 1; break;
		case'*': case'/':  k = 2; break;
		case'#': k = 0;    break; 	
	}
	return k;
}

int jisuan(int a,int b,char c){
	switch(c){                     //确定四则运算 
		case'+': return a+b;break;
		case'-': return a-b;break;
		case'*': return a*b;break;
		case'/': return a/b;break;	
		default: break;
	}
}

int  qiuZhi(char s[]){
	stack<char> s1,s2,s3;         //s1暂定存储数字栈,s2暂定存储符号栈,s3转换后的后缀表达式 
	stack<int>  s4;              //后缀表达式运算的数字存储栈 
	s2.push('#');
	for(int i = 0;i<strlen(s);i++){      
	    if(s[i]>='0'&&s[i]<='9'){   
	    	s1.push(s[i]);      //数据段压入
		}  
		if(s[i]=='('){        //左单括号直接压入s2暂定符号栈 
			s2.push('(');     
		}
		if(s[i]==')'){
			while(s2.top()!='('){
			    char c = s2.top();
			    s1.push(c);
				s2.pop();
			}
			s2.pop();                                         //注意:将左单括号弹出 
		}
		if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){     //(+,-,*,/)要与暂定符号栈s2栈顶元素对比优先级 
		    if(s2.top()=='('){    
		    	s2.push(s[i]);
			}
		    else{ 	
				while(true){                     //循环到s[i]优先级大于暂定符号栈s2的栈顶元素,并将s[i]压入s2 
					if(youXianJi(s[i])<=youXianJi(s2.top())){
			    	     char item = s2.top();
			    	     s1.push(item);
			    	     s2.pop();   
				    }
					else{
						s2.push(s[i]);
						break;      
					}	
				}									 
	        }
		}   
	} 
		while(s2.top()!='#'){                 //将暂定符号栈s2中全部元素压入s1,得到的s1为后缀表达式的逆序 
			s1.push(s2.top());
			s2.pop();
		}
        while(!s1.empty()){                  //s1逆序得到s3;s3为表达式的最终后缀表达式 
        	  s3.push(s1.top());
        	  s1.pop();
		}
		 
        while(!s3.empty()){                 //s4为最终数字存储栈 
       	    if('0'<=s3.top()&&s3.top()<='9'){
       	    	s4.push(s3.top()-'0');
       	    	s3.pop();
       	    }
       	    else{
       	            int a = s4.top();
				    s4.pop();
				    int b = s4.top();
				    s4.pop();
				    int c = jisuan(b,a,s3.top()); 
					s3.pop();
					s4.push(c);
			}
	    }
    return s4.top();
}

int main(int argc, char** argv) {
    char s[20];
    printf("输入中缀表达式:\n");
	scanf("%s",s);
	for(int i = 0;i<strlen(s);i++){
		printf("%c",s[i]);
	}
	printf("=%d\n",qiuZhi(s));
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值