繁体   English   中英

后缀算法的中缀

[英]Infix to postfix algorithm

我一直在研究一种将“ a + b * cd / e”转换为后缀形式的算法。 我已经准备好http://en.wikipedia.org/wiki/Shunting-yard_algorithm Wiki,但是我的逻辑存在问题。 当我打印出队列时,没有操作符,我将得到“ abcde”。 似乎没有什么东西被推入我的堆栈? 否则,它不会被推送到我的队列中。 我创建的双链表类正在实现我的队列/堆栈。

#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;
}

您的代码部分::

        if(oper(temp)<oper(prev))
        {
        newstring->queue(holder->popStack());
        temp = '\0';
        continue;
        }   

这部分代码完全无效……输入“ a + b * cd / e”中提供的字符串

看到这个::

 if(oper(temp)<oper(prev))

条件是检查变量temp中前一个操作符相对于当前扫描的操作符的优先级,但是前一个if语句(堆栈为空的条件)之外没有语句可从可用选项中提取或分配prev变量在堆栈中,因此初始值“ +”用于评估if条件,该条件小于“ *”和“ \\”,并且与“-”处于同一水平,但第二个if条件永远不会满足,剂量也会受到打击。

多数民众赞成在多数民众赞成在多数民众赞成在多数民众赞成这就是为什么当你弹出没有什么堆栈,这就是你如何获得当前的结果。 您将需要再次访问代码并进行适当的更改。

希望对您有所帮助,祝您有美好的一天。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM