Infix to postfix conversion using stack【1月21日学习笔记】

点击查看代码
//Infix to postfix conversion using stack
#include<iostream>
#include<stack>//stack from standard template library(STL)
#include<string>
using namespace std;

string InfixToPostfix(string exp);

bool HasHigherPrecedence(char opr1, char opr2);

bool IsOperator(char c);

bool IsOperand(char c);

int  GetOperatorWeight(char op);

bool IsRightAssociative(char opr);

int main() {
	string expression;
	getline(cin, expression);//与cin>>不同,可以读取空格,直到整行换行符结束
	cout << "Output = " << InfixToPostfix(expression) << "\n";
}

string InfixToPostfix(string exp) {
	stack<char> S;//保存运算符及括号
	string postfix = "";//初始化为空

	for (int i = 0; i < exp.length(); i++) {
		if (exp[i] == ' ' || exp[i] == ',')  continue;
		else if (IsOperator(exp[i])) {
			while (!S.empty() && S.top() != '(' && S.top() != '[' && S.top() != '{' && HasHigherPrecedence(S.top(), exp[i])) {//依次拿出优先级较高(优先级相同时则左结合)运算符放入表达式至碰到开括号
				postfix += S.top();//string的添加操作
				S.pop();
			}
			S.push(exp[i]);//将此运算符放入stack(stack中运算符优先级高的在上面)
		}
		else if (IsOperand(exp[i])) {//直接放入操作数
			postfix += exp[i];
		}
		else if (exp[i] == '('|| exp[i] == '[' || exp[i] == '{' ) {//直接放入开括号
			S.push(exp[i]);
		}
		else if (exp[i] == ')') {//扫描到闭括号则一直pop到开括号
			while (!S.empty() && S.top() != '(') {
				postfix += S.top();
				S.pop();
			}
			S.pop();//pop掉匹配的开括号
		}
		else if (exp[i] == ']') {
			while (!S.empty() && S.top() != '[') {
				postfix += S.top();
				S.pop();
			}
			S.pop();
		}
		else if (exp[i] == '}') {
			while (!S.empty() && S.top() != '{') {
				postfix += S.top();
				S.pop();
			}
			S.pop();
		}
	}

	while (!S.empty()) {//剩下的直接放入
		postfix += S.top();
		S.pop();
	}
	return postfix;
}

bool HasHigherPrecedence(char opr1, char opr2) {
	int w1 = GetOperatorWeight(opr1);
	int w2 = GetOperatorWeight(opr2);
	
	if (w1 == w2) {//优先级相同时则左结合
		if (IsRightAssociative(opr1)) return false;
	    return true;
	}
	return w1 > w2 ? true : false;
}

int  GetOperatorWeight(char opr) {//定义优先级
	int weight = -1;
	switch(opr) {
	case '+':
	case '-':
		weight = 1; break;
	case '*':
	case '/':
		weight = 2; break;
	case '^':
		weight = 3; break;
	//可添加其他运算
	}
	return weight;
}

bool IsRightAssociative(char opr) {
	if (opr == '^')  return true;
	return false;
}

bool IsOperator(char c) {
	if (c == '+' || c == '-' || c == '*' || c == '/'||c=='^')  return true;
	return false;
}

bool IsOperand(char c) {
	if (c >= '0' && c <= '9')  return true;
	return false;
}
posted @   bituion  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示