我需要实现中缀到后缀转换算法来计算表达式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);
}
答案 0 :(得分:2)
我认为这是一项家庭作业,所以你自己弄清楚编程细节是很重要的。该算法的概要如下:
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.
答案 1 :(得分:0)
我认为你应该创建一个运算符和值的树 您可以根据树的遍历顺序从中缀转换为后缀到前缀 您的教练可能会给您指定三者之间的转换。
以下是一些文章:
University of Texas
YouTube video
Wikipedia - Expression trees