需要创建中缀到后缀的算法

Need to create infix to postfix algorithm

本文关键字:后缀 算法 中缀 创建      更新时间:2023-10-16

我需要实现中缀到后缀的转换算法来计算表达式a+b*c-d/e

我还需要使用queue(我相信需要2个不同的队列堆栈)

我已经使用DoubleLinkList创建了我的队列类,现在只需要为这个问题创建算法。不过我不知道该怎么做。任何帮助将不胜感激!

到目前为止(我知道这是非常错误的)我有:

string infix = "a+b*c-d/e";
    Queue *holder = new Queue();
    Queue *newstring = new Queue();
    int length = infix.length();
    char temp;
    char prev;
    for(int i=0; i<length; i++)
    {
        temp = infix[i];
        if((temp == '+') || (temp == '-') || (temp == '*') || (temp == '/'))
        {
            if (holder->isEmpty())
            {
                holder->queue(temp);
            }
            if(temp<holder.enqueue())
            {
            }
        }
        holder->queue(temp);
    }

我认为这是一个家庭作业,所以重要的是你自己找出编程细节。算法概要如下:

Define a stack
Go through each character in the string
If it is between 0 to 9, append it to output string.
If it is left brace push to stack
If it is operator *+-/ then 
          If the stack is empty push it to the stack
          If the stack is not empty then start a loop:
                             If the top of the stack has higher precedence
                             Then pop and append to output string
                             Else break
                     Push to the stack
If it is right brace then
            While stack not empty and top not equal to left brace
            Pop from stack and append to output string
            Finally pop out the left brace.
If there is any input in the stack pop and append to the output string.

我认为你应该创建一个操作符和值的树。
您可以根据树的遍历顺序从中缀转换为后缀再转换为前缀。
你的老师可能会给你布置作业,让你在三者之间进行转换。

这里有一些文章:
德克萨斯大学
YouTube视频
Wikipedia -表达式树