DS栈的应用——四则表达式
我们把平时所用的标准四则运算表达式,即 “9+ (3-1) ×3 + 10 ÷ 2” 叫做中缀表达式。
因为所有的运算符号都在两数字中间,现在我们要进行中缀到后缀的转化。
中缀表达式 “9+(3-1) × 3+10÷2” 转化为后缀表达式 “9 3 1 - 3* + 10 2 / +”
算法思想:从左到右遍历中缀表达式的每个数字和符号,若是数字就输出,即成为后缀表达式的一部分;若是符号,则判断其与栈顶符号的优先级,是右括号或优先级低于栈顶符号则栈顶元素依次出栈并输出,并将当前符号进栈,一直到最终输出后缀表达式为止。
代码实现:
void NiBolan(string str)
{
stack<char>stk;
char ch;
for (int i = 0; i < str.length(); i++)
{
ch = str[i];
int j = i;
if (ch >= 48 && ch <= 57)
{
cout << ch;
while (str[j + 1] >= 48 && str[j + 1] <= 57)
{
cout << str[++j];
}
i = j;
cout << ' ';
continue;
}
else
{
if (stk.empty())
{
stk.push(ch);
continue;
}
else if (pairs[ch] > pairs[stk.top()])
{
stk.push(ch);
continue;
}
else if (ch == '(')
{
stk.push(ch);
}
else if (ch == ')')
{
while (stk.top() != '(')
{
cout << stk.top() << ' ';
stk.pop();
}
stk.pop();
}
else
{
if (stk.empty())
{
stk.push(ch);
continue;
}
if (pairs[ch] >= pairs[stk.top()])
{
stk.push(ch);
continue;
}
else
{
while (pairs[ch] <= pairs[stk.top()])
{
cout << stk.top() << ' ';
stk.pop();
if (stk.empty())
break;
}
stk.push(ch);
}
}
}
}
while (!stk.empty())
{
if (stk.size() > 1)
cout << stk.top() << ' ';
else
cout << stk.top();
stk.pop();
}
cout << endl;
}```