表示式

ProtectEMmm發表於2024-09-02

表示式

獲取優先順序

int GetPriority(char c)
{
	if (c == '*')return 0;
	if (c == '+')return -1;
	return -2;
}

中綴轉字尾

string PostfixExpression(string str)
{
	string res;
	stack<char>stk;
	for (auto c : str)
	{
		if (c == '_')
		{
			res.push_back(c);
		}
		if (c == '(' || c == ')')
		{
			if (c == '(')
			{
				stk.push('(');
			}
			if (c == ')')
			{
				while (!stk.empty() && stk.top() != '(')
				{
					res.push_back(stk.top()); stk.pop();
				}
				stk.pop();
			}
		}
		if (c == '+' || c == '*')
		{
			while (!stk.empty() && GetPriority(stk.top()) >= GetPriority(c))
			{
				res.push_back(stk.top()); stk.pop();
			}
			stk.push(c);
		}
	}
	while (!stk.empty())
	{
		res.push_back(stk.top()); stk.pop();
	}
	return res;
}

建立表示式樹

struct Node
{
	int val;
	char tag;
	Node* lch, * rch;
	Node(int _val = 0, char _tag = ' ', Node* _lch = NULL, Node* _rch = NULL)
	{
		val = _val, tag = _tag;
		lch = _lch, rch = _rch;
	}
};
Node* Build(string str)
{
	stack<Node*>stk;
	for (auto c : str)
	{
		if (c == '0' || c == '1')
		{
			stk.push(new Node(c - '0', ' ', NULL, NULL));
		}
		else
		{
			Node* rch = stk.top(); stk.pop();
			Node* lch = stk.top(); stk.pop();
			stk.push(new Node(((c == '&') ? (lch->val & rch->val) : (lch->val | rch->val)), c, lch, rch));
		}
	}
	return stk.top();
}

相關文章