所以我正在研究一个带有中缀表达式并将其转换为后缀表达式的程序。这意味着当我输入a + b时,输出将是ab +,并且我无法找到正确打印出来的方法,因为我无法想出一种对字母进行排序的方法,比如我如何将输入a + bc转换为ab + c-而不是abc + - ?源代码仍在进行中。
#include <iostream>
#include <stack>
using namespace std;
int prec(char in)
{
switch(in) {
case '(': return 0;
case '+':
case '-': return 1;
case '*':
case '/': return 2;
default : return 3;
}
}
int main()
{
stack <char> ops;
//stack <char> high-ops;
char next_character ;
while(!cin.eof()) {
cin >> next_character;
if(next_character =='(' )
ops.push('(');
else if(next_character == ')') {
while(!ops.empty() && ops.top() != '(') {
cout << ops.top();
ops.pop();
}
if(!ops.empty())
ops.pop();
else
cout << "Error/n";
}
if((next_character >= 'a' && next_character <= 'z') || (next_character >= 'A' && next_character <= 'Z') || (next_character >= '0' && next_character <= '9'))
if(next_character == '*' || next_character == '/' || next_character == '+' || next_character == '-') {
if(ops.empty())
ops.push(next_character);
if(prec(next_character) > prec(ops.top()))
ops.push(next_character);
if(prec(ops.top()) > prec(next_character)) {
cout << ops.top();
ops.pop();
if( prec(ops.top()) == prec(next_character)){
ops.push(next_character);
cout << ops.top();
ops.pop();
}
}
}
//if(!ops.empty())
//ops.push(next_character);
}
while(!ops.empty()){
cout << ops.top();
ops.pop();
}
}
答案 0 :(得分:-1)
您需要递归解析,而不是基于堆栈的解析。
在伪代码中,它看起来像这样:
func reorder(expression)
if whole_expression_is_wrapped_with_parentheses
return reorder(expression without wrapping parentheses)
if exists_operator(expression)
oi = operator_index = find_operator(expression)
before = expression.substring(0 to oi-1, including)
operator = expression.charAt(oi)
after = expression.substring(oi + 1 to end of string)
return reorder(before) + reorder(after) + oi
return expression
func exists_operator(expression)
Simply check if any operator is in the expression out of parentheses.
func find_operator(expression)
Return the id of the first operator found out of parentheses.
To implement precedence, ignore lower precedence operators until making sure no higher precedence operators are in the expression
两个辅助函数应该使用基于堆栈的括号计数器来实现,以确保只搜索任何括号。