ii沙漠

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
//输入的时候加不加空格都行,因为是前缀表达式.
//但是输出中应该要加空格,因为有可能几个数字是挨在一起的情况.


//has not complete the `to_prifix`, because i do not know how to do it.

#include <iostream>
#include <string>
#include <cctype>
#include <stack>
using namespace std;

class Compute{
public:
	Compute(string infix_);
	int Cal();
	string Prefix() { return prefix; }
	string Postfix() { return postfix; }
private:
	string prefix;
	string infix;
	string postfix;
private:
	void to_postfix();
	int cal(int n1, int n2, char c);
	int compare_priory(char x, char y);
};

Compute::Compute(string infix_) : infix(infix_)
{
	to_postfix();
}

int Compute::cal(int n1, int n2, char c)
{
	switch (c){
	case '+': return n1 + n2;
	case '-': return n1 - n2;
	case '*': return n1 * n2;
	case '/': return n1 / n2;
	}
}



int Compute::compare_priory(char x, char y)
{
	if (x == '*' || x == '/') return 1;
       else if ((x == '+' || x == '-') && (y == '+' || y == '-')) return 1;
       else return 0;
}


void Compute::to_postfix()
{
	stack<char> optr;

	int len = infix.length();
	int i;
	for (i = 0; i < len; i++){
		if (infix[i] == ' ') {
			continue;
		} else if (isdigit(infix[i])){
			if (i > 0 && (!isdigit(infix[i-1]))){
				postfix.push_back(' ');
				postfix.push_back(infix[i]);
			}else 
				postfix.push_back(infix[i]);
		} else {
			if (optr.empty() || compare_priory(infix[i], optr.top())){
				optr.push(infix[i]);
			}else {
				while (!optr.empty() && compare_priory(optr.top(), infix[i])){
					postfix.push_back(' ');
					postfix.push_back(optr.top());
					postfix.push_back(' ');
					optr.pop();
				}
				optr.push(infix[i]);
			}
		}
	}
	while (!optr.empty()){
		postfix.push_back(' ');
		postfix.push_back(optr.top());
		postfix.push_back(' ');
		optr.pop();
	}
	if (postfix.back() == ' ') postfix.pop_back();
}

int Compute::Cal()
{
	int len = postfix.length();
	if (len == 0) return 0;

	stack<int> s;
	int i;
	int nu = 0;
	for (i = 0; i < len; i ++){
		nu = 0;
		if (postfix[i] == ' ')
			continue;
		else if (isdigit(postfix[i])){
			if (i > 0 && isdigit(postfix[i-1]) && !s.empty()){
				nu = s.top();
				nu = nu * 10 + postfix[i] - '0';
				s.pop();
				s.push(nu);
			}else 
				s.push(postfix[i] - '0');
		}else{
			int n1 = s.top(); s.pop();
			int n2 = s.top(); s.pop();
			s.push(cal(n2, n1, postfix[i]));
		}
	}
	return s.top();
}
			


int main()
{
	Compute c("12 * 3 + 24 * 35 / 5 - 46");
	cout << c.Postfix() << endl;
	cout << "the result is " << c.Cal() << endl;
	return 0;
}
posted on 2015-08-13 16:39  ii沙漠  阅读(214)  评论(0编辑  收藏  举报