中缀转后缀并计算

#include<iostream>
#include<stack>
#include<sstream> 
using namespace std;	
bool isNum(char num) {//判断当前字符是否为数字 
    return (num>='0'&&num<='9')?true:false;
}
int pri(char op) {//+-优先级为1,*/优先级为2 
   	return (op=='+'||op=='-')?1:2;
}   
bool cmp(char op,stack<char>st) {//判断栈顶元素与即将要压入栈的元素优先级 
   	if(st.empty()||st.top()=='('||(pri(op)) > (pri(st.top()))) {
    	return true;
   	}else {
   		return false;
   	}
}
int strToNum(string str){//将数字字符串转换为对应的整数类型
	stringstream ss;
    ss<<str;
    int op;
    ss>>op;
    return op;
}
string midToAfter(string s) //将一个中缀表达式转换为后缀表达式
   stack<char>sta;
   string res = "";
   for(int i = 0; i < s.length();) {
	   	if(s[i] == ' '){
	   		i++;
	   		continue;
	   	}
	   	if(isNum(s[i])) {
	   		string temp = "";
	   		while(isNum(s[i])) {
	   			temp += s[i];
	   			i++;
	   		}
	   		temp+='_';
	   		res += temp;
	   	} else {
	   		if(s[i]=='('){
	   		    sta.push(s[i]);
	   		}else if(s[i]!= ')') {
	   			if(cmp(s[i],sta)) {
	   				sta.push(s[i]);
	   			} else {
	   				while(!cmp(s[i],sta)) {    					
					   	res += sta.top();
	   					sta.pop();
	   				}
	   				sta.push(s[i]);
	   			}
	   		} else{
	   			while(sta.top()!='(') {
	   				res += sta.top();
	   				sta.pop();
	   			}
	   			sta.pop();
	   		}
	   		i++;
	   	}
   	}
   	while(!sta.empty()) {
   		res += sta.top();
   		sta.pop();
   	}
   	return res;
}
int jisuan(char op,int a,int b) {//计算两个数
    return (op=='+') ? a+b :(op=='-')?b-a:(op=='*')?a*b:b/a;
}
int result(string s) {//计算后缀表达式
  	s = midToAfter(s);
    stack<int>num;
   	int len = s.length();
   	if(len == 0){
   	    return 0;
   	}    	
	for(int i = 0; i < len;) {
   		if(isNum(s[i])) {
    		string str = "";
    		while(isNum(s[i])) {
    			str += s[i];
    			i++;
    		}
   			num.push(strToNum(str));
   		} else if(s[i]!='_') {
   			int a = num.top();
   			num.pop();
   			int b = num.top();
   			num.pop();
   			num.push(jisuan(s[i],a,b));
   			i++;
   		} else {
   			i++;
   		}
   	}
   	return num.top();
}
int main(){
	string op;
	cout<<"请输入一个表达式:"<<endl;
	cin>>op;
	cout<<result(op)<<endl; 
	return 0; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值