我一直致力于将“a + b * c-d / e”转换为后缀形式的算法。我已准备好http://en.wikipedia.org/wiki/Shunting-yard_algorithm wiki,但我的逻辑存在问题。当我打印出我的队列时,我得到了“没有操作员”的“b b d e”。似乎没有什么东西被推入我的堆栈?或者如果是,它不会被推入我的队列。我的队列/堆栈是由我创建的双链表实现的。
#include <iostream>
#include "LinkedList.h"
#include "Stack.h"
#include "Queue.h"
using namespace std;
int oper(char c)
{
switch(c) {
case '!':
return 4;
case '*': case '/': case '%':
return 3;
case '+': case '-':
return 2;
case '=':
return 1;
}
return 0;
}
int main () {
LinkedList* list = new LinkedList();
string infix = "a+b*c-d/e";
Stack *holder = new Stack();
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->push(temp);
prev = temp;
continue;
}
if(oper(temp)<oper(prev))
{
newstring->queue(holder->popStack());
temp = '\0';
continue;
}
else
holder->push(temp);
prev = temp;
}
else
newstring->queue(temp);
}
while(!holder->isEmpty())
{
newstring->queue(holder->popStack());
}
newstring->printQueue();
return 0;
}
答案 0 :(得分:1)
你的代码部分::
if(oper(temp)<oper(prev))
{
newstring->queue(holder->popStack());
temp = '\0';
continue;
}
代码中的这一部分一定会受到打击...... 输入中提供的字符串&#34; a + b * c-d / e&#34;
见这个::
if(oper(temp)<oper(prev))
条件是检查前一个运算符相对于变量temp中当前扫描的优先级的优先级,但是在前一个if语句之外没有语句(stack为空的条件)以从中提取或分配prev变量堆栈中可用的选项因此初始值为&#34; +&#34;用于评估if条件小于&#34; *&#34;和&#34; \&#34; ,与#34; - &#34;处于同一水平但结果并不是更大,第二个if条件永远不会得到满足而且剂量会受到打击。
这可能就是为什么当你弹出任何东西时都会从堆栈中出来,这就是你如何获得当前结果的原因。您需要再次访问该代码并进行适当的更改。
希望这会有所帮助,祝你今晚愉快。