数据结构与算法分析 c++11 练习3.22 中缀表达式转后缀表达式,后缀表达式计算, 多项式计算

 练习3.22 中缀表达式转后缀表达式,后缀表达式计算, 多项式计算



polynome.h

#pragma once
#include <string>
#include <stack>  
#include <cctype>//判断字符类型需要的头文件
#include <vector>
#include <sstream>
#include <cstdlib>

class Polynome {
public:
	Polynome() = default;
	Polynome(std::string str) :infix(str) { }
	
	std::string infixToPostfix();
	float getResultUsePostfix();

	~Polynome() {}
protected:
	void processOperator(std::string &s, char opera );
	void CalculateResult(const char *oper, std::stack<double>& tmpStack);
	bool isPriorityLow(char currOper, char topOper);
	bool isNumber(char s);
	void split(const std::string& strOrignal, const char ch, std::vector<std::string>& vctString);
private:
	std::stack<char> operators;
	std::string infix;
	std::string postfix;
};


polynome.cpp


#include "polynome.h"
using namespace std;
string Polynome::infixToPostfix()
{

	for (size_t i = 0; i < infix.length(); i++) {
		if (isNumber(infix[i])) {           
			postfix += infix[i];
		}
		else {
			postfix += ' ';
			processOperator(postfix, infix[i]);  
		}
	}
	
	if (postfix.length() > 0) {
		while (operators.size() > 0) {
			postfix += ' ';
			postfix += operators.top();
			operators.pop();
		}
		return postfix;
	}else {
		return "";
	}

}

float Polynome::getResultUsePostfix()
{
	if (postfix.length() <= 0) {
		return 0;
	}
	stack<double> tmpStack;
	double dbl;
	vector <string> temVec;
	split(postfix, ' ', temVec);
	for (size_t i = 0; i < temVec.size(); i++) {
		if(temVec[i]=="+"|| temVec[i] == "-"|| temVec[i] == "*"|| temVec[i]== "/")
		{
			CalculateResult(temVec[i].c_str(), tmpStack);
		}
		else {
			dbl = atof(temVec[i].c_str());
			tmpStack.push(dbl);
		}
	}
	return tmpStack.top();
}

void Polynome::processOperator(string & s, char opera)
{
	switch (opera) {
	case '+':
	case '-':
	case '*':
	case '/':
		if (operators.size() <= 0) {
			operators.push(opera);
		}
		else if (isPriorityLow(opera, operators.top())) {
			while (operators.size() > 0 && isPriorityLow(opera, operators.top())) {
				s += operators.top();
				s += ' ';
				operators.pop();
			}
			operators.push(opera);
		}
		else {
			operators.push(opera);
		}
		break;
	case('('):
		operators.push(opera);
		break;
	case(')'):
		//将栈中元素弹出加到后缀表达式尾,直到遇到运算符"("
		while (operators.top() != '(') {
			s += operators.top();
			operators.pop();
		}
		operators.pop();
		break;
	}

}

void Polynome::CalculateResult(const char* oper, stack<double>& tmpStack)
{
	if (tmpStack.size() < 2) {
		return;
	}
	//栈是先进后出,所以先弹出的是第二个值
	double secondVal = tmpStack.top();
	tmpStack.pop();
	double firstVal = tmpStack.top();
	tmpStack.pop();

	double result = 0;
	switch (*oper) {
	case '+':
		result = firstVal + secondVal;
		break;
	case '-':
		result = firstVal - secondVal;
		break;
	case '*':
		result = firstVal * secondVal;
		break;
	case '/':
		result = firstVal / secondVal;
		break;
	default:
		break;
	}

	tmpStack.push(result);
}

/**
* 判断当前运算符与栈顶运算符的优先级大小
*/
bool Polynome::isPriorityLow(char currOper, char topOper)
{
	if (currOper == '+' || currOper == '-') {
		if (topOper == '*' || topOper == '/' || topOper == '+' || topOper == '-') {
			return true;
		}
	}

	if (currOper == '*' || currOper == '/') {
		if (topOper == '*' || topOper == '/') {
			return true;
		}
	}
	return false;
}

bool Polynome::isNumber(char s)
{
	string opers = "+-*/()^";
	for (int i = 0; i < opers.length(); i++) {
		if (s == opers.at(i)) {
			return false;
		}
	}
	return true;
}

void Polynome::split(const string & strOrignal,const char ch, std::vector<string>& vctString)
{
	istringstream iss(strOrignal);
	string item;
	while (getline(iss, item, ch)) vctString.push_back(item);

	stringstream stream;
	stream << ch;           
	auto it = vctString.begin();
	while (it != vctString.end())
	{
		if (*it ==stream.str()|| *it =="")               //将char 转化为string
			it = vctString.erase(it);
		else
			it++;
	}
	return;
}

main.cpp

#include <iostream>  

#include <stdio.h>  
#include <stdlib.h>  

#include "polynome.h"

using namespace std;

int main()
{

	string infix = {"4.99*1.06+5.99+6.99*1.06"};
	string infix1 = { "a+b*c+(d*e+f)*g" };
	cout << "请输入多项式(不要空格):" << endl;
	while(1)
	{
	string infix3;
	string postfix;
	cin >> infix3;
	Polynome inf(infix3);
	postfix = inf.infixToPostfix();
	cout <<"后缀表达式为:"<< postfix << endl;
	float result = inf.getResultUsePostfix();
	cout << "计算结果为: " << result << endl;
	}
	

	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值