一种根据输入的顺序分组输入的方法

A way to sort out inputs according to the order they are inputted?

本文关键字:输入 顺序 方法 一种      更新时间:2023-10-16

,所以我正在研究一个程序,该程序将infix表达式并将其转换为后缀表达式。意思是当我输入A B时,输出将为AB ,并且我无法找到正确打印出来的方法,因为我无法想到一种分类字母的方法,例如如何将输入A B-C转换为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();  
}

}

您需要递归解析,而不是基于堆栈的解析。

在psuedo代码中,看起来像这样:

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

应使用基于堆栈的括号计数器实现两个辅助功能,以确保您仅搜索任何括号。