0

这是我的第一个问题,所以请原谅非技术语言
,我正在制作一个将中缀转换为前缀和后缀的程序。我对正在工作的后缀做了中缀。现在,当我想中缀前缀时,我们需要反转表达式。所以我想从相反的方向阅读中缀。

while(*e != '\0')
    {
        if(isalpha(*e))
            printf("%c ",*e);
        else if(*e == '(')
            push(*e);
        else if(*e == ')')
        {
            while((x = pop()) != '(')
                printf("%c ", x);
        }
        else
        {
            while(priority(stack[top]) >= priority(*e))
                printf("%c ",pop());
            push(*e);
        }
        e++;
    }  

以上是后缀中缀的一部分,其中e 是扫描字符串的指针。在 pre 的中缀中,我计划将 e++ 替换为 e-- 但正如在第一行中我们看到它直接打印 char 所以我需要反转方向
例如。
咩 +

4

1 回答 1

-1

First, welcome to stackoverflow. (I am also new here.)

Actually, your title doesn't quite describe what you need: that is, "writing in reverse direction" is not sufficient for your goals.

Consider the input infix expression a + b * c. You've accomplished the sub-task of converting this to postfix as a b c * + (assuming the precedence of * is higher than +). A correct conversion to prefix would be + a * b c. Notice that this is not the same as a reversal of the postfix result (i.e., it is not + * c b a). To conclude, a prefix expression is not merely a reversal of a postfix expression.

So, how would I solve your task? I would create a system with three components. The first component processes your input and generates a simple "parse tree", which is graphically represented as:

  +  
 / \
a   *
   / \  
  b   c

The main data structure for this is a "parse tree node" that looks something like this:

struct Node {
    Node* leftChild;
    Node* rightChild;
    char symbol;
};

The second component converts from this parse tree into a postfix expression (accomplishing the same as what your original post did).

The third component converts from this parse tree into a prefix expression. To do so is simply a recursive process (given a particular node, output that node's symbol first, then recursively apply to the left side, then recursively apply to the right side). Please let me know if you need any further guidance on how to do this.

于 2021-03-07T19:09:58.077 回答