表达式
获取优先级
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();
}
标签:Node,val,top,stk,rch,lch,表达式
From: https://www.cnblogs.com/ProtectEMmm/p/18360923