中缀到后缀算法
Infix to postfix algorithm
我一直在研究一种将"a+b*c-d/e"转换为后缀形式的算法。我已经准备好http://en.wikipedia.org/wiki/Shunting-yard_algorithm维基,但我有我的逻辑问题。当我打印出我的Queue时,我得到的是没有操作符的"a b c d e"。我的堆栈里好像没有东西?如果是,它不会被推送到我的Queue中。我的队列/堆栈是由我创建的双链表类实现的。
#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 = ' ';
continue;
}
else
holder->push(temp);
prev = temp;
}
else
newstring->queue(temp);
}
while(!holder->isEmpty())
{
newstring->queue(holder->popStack());
}
newstring->printQueue();
return 0;
}
你的代码::
if(oper(temp)<oper(prev))
{
newstring->queue(holder->popStack());
temp = ' ';
continue;
}
这部分代码根本没有命中......输入"a+b*c-d/e"中提供的字符串
参见::
if(oper(temp)<oper(prev))
条件是检查前一个操作符相对于变量temp中当前扫描的操作符的优先级,但是在前一个if语句(堆栈为空的条件)之外没有语句从堆栈中可用的选项中提取或分配前一个变量,因此"+"的初始值用于计算小于"*"answers""的if条件。And与"-"处于同一级别,但不大于"-",因此第二个if条件永远不会得到满足,也不会得到命中。
这可能就是为什么当你弹出时没有任何东西从堆栈中取出,这就是你得到当前结果的方式。您需要再次访问代码并进行适当的更改。
希望这对你有帮助,祝你今天愉快。
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 算法问题:查找从堆栈中弹出的所有序列
- 下面是排序算法O(n)吗
- KMP算法和LPS表构造的运行时间
- 为什么我的排序算法会更改数组值
- 高效的字符串截断算法,按顺序删除相等的前缀和后缀
- 后缀评估算法
- 使用后缀数组算法进行Burrows-Wheeler变换
- Ukkonen的后缀树算法,有什么必要?
- 后缀数组算法
- 找出后缀数组的两种算法中哪一种更快,为什么?
- 中缀到后缀算法
- 需要创建中缀到后缀的算法