逆波兰表达式

逆波兰表达式:后缀表达式

波兰表达式:前缀表达式


计算后缀表达式:

当遇到一个数时就把它压入栈中,在遇到一个操作符时就将该操作符作用于该栈弹出的两个数上,并将结果压入栈中。

#include<stack>
double evalPostFix( )
{
	stack<double> s;
	string token;
	double a, b, result;
	cin>> token;
	while (token[0] != '=')
	{
		result = atof (token.c_str());
		if (result != 0.0 )
			s.push(result);
		else if (token == "0.0")
			s.push(result);
		else
			switch (token[0])
			{
			case '+' : a = s.top(); s.pop(); b = s.top();
					   s.pop(); s.push(b+a); break;
			case '-' : a = s.top(); s.pop(); b = s.top();
					   s.pop(); s.push(b-a); break;
			case '*' : a = s.top(); s.pop(); b = s.top();
				       s.pop(); s.push(a*b); break;
			case '/' : a = s.top(); s.pop(); b = s.top();
					   s.pop(); s.push(b/a); break;
			case '^' : a = s.top(); s.pop(); b = s.top();
					   s.pop(); s.push(exp(b*log(a))); break;
			}
		cin>> token;
	}
	return s.top();
}


中缀变后缀:

当读到一个操作数时,立即输出;当遇到操作符时,从栈中弹出并输出元素直到遇到优先级更低的操作符,该操作符进栈。对于“(”,将其压入栈中,除非是在处理“)”的时候,否则决不从栈中移走“(”,最后,如果读到输入的末尾,将栈元素弹出直到空栈。

int main()
{
	stack<char> s;
	char token;
	cin>> token;
	while (token != '=')
	{
		if (token >= 'a' && token <= 'z')
			cout<<token<<" ";
		else
			switch (token)
			{
			case ')' : while(!s.empty() && s.top() != '(')
					    { cout<<s.top()<<" "; s.pop();}
					    s.pop(); break;
			case '(' : s.push(token); break;
			case '^' : while(!s.empty() && s.top()== '^')
						{cout<<s.top()<<" "; s.pop();}
						s.push(token); break;
			case '*' :
			case '/' : while(!s.empty() && s.top() != '+' && s.top() != '-' && s.top() != '(')
						{cout<<s.top()<<" "; s.pop();}
						s.push(token); break;

			case '+' :
			case '-' : while(!s.empty() && s.top() != '(' )
						{cout<<s.top()<<" "; s.pop();}
						s.push(token); break;
			}
		cin>> token;
	}
	while (!s.empty())
		{cout<<s.top()<<" "; s.pop();}
	cout<<"="<<endl;
	return 0;
}


后缀变中缀:

跟计算后缀表达式差不多,只不过将操作数取出来的时候组成字符串压入栈中:

string postToInfix()
{
	stack<string> s;
	string token;
	string a, b;
	cin>>token;
	while (token[0] != '=')
	{
		if (token[0] >= 'a' && token[0] <= 'z')
			s.push(token);
		else
			switch (token[0])
			{		
			case '+' : a = s.top(); s.pop(); b = s.top(); s.pop();
						s.push("("+ a+" + " + b+")"); break;
			case'-' : a = s.top(); s.pop(); b = s.top(); s.pop();
						s.push("("+a+" - "+ b+")"); break;
			case '*' : a = s.top(); s.pop(); b = s.top(); s.pop();
						s.push("("+a+" * "+ b+")"); break;
			case '/' : a = s.top(); s.pop(); b = s.top(); s.pop();
						s.push("("+a+" / " + b+")"); break;
			case '^' : a = s.top(); s.pop(); b = s.top(); s.pop();
						s.push("("+a+" ^ " + b+")"); break;
			}
		cin>> token;
	}
	return s.top();
}


后缀变前缀:

原理同上。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值