栈的应用-后缀表达式求值(简单表达式)

91 阅读1分钟
int calc(string str){
	stack<int>s;
	int i=0,a,b,num=0;
	while(i<str.size()){
		if(str[i]>'0'&&str[i]<'9'){
			num=str[i]-'0';
			s.push(num);
			i++;
		}
		else{
			a=s.top();
			s.pop();
			b=s.top();
			s.pop();
		    switch(str[i]) {
	            case '*': 
	                s.push(a*b);
	                break;
	            case '/':
	                s.push(b/a);
	                break;
	            case '+':
	                s.push(a+b);
	                break;
	            case '-':
	                s.push(b-a);
	                break;
        }
        	i ++;
		}
	}
	return s.top();
}