gpt4 book ai didi

c++ - 需要创建中缀到后缀算法

转载 作者:行者123 更新时间:2023-11-28 03:21:05 26 4
gpt4 key购买 nike

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

我还需要使用队列来做到这一点(我相信需要 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.

关于c++ - 需要创建中缀到后缀算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15416142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com