中缀到后缀算法

Infix to postfix algorithm

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

我一直在研究一种将"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条件永远不会得到满足,也不会得到命中。

这可能就是为什么当你弹出时没有任何东西从堆栈中取出,这就是你得到当前结果的方式。您需要再次访问代码并进行适当的更改。

希望这对你有帮助,祝你今天愉快。