简体   繁体   English

C ++中的中缀到后缀转换器没有输出

[英]Infix to Postfix Converter in C++ gives no output

I made a function infixToPostfix() which converts an infix expression to a postfix expression.我制作了一个函数infixToPostfix() ,它将中缀表达式转换为后缀表达式。 But my program generates no output on running.但是我的程序在运行时不会产生任何输出。 Please point out the errors in my program.请指出我程序中的错误。

Code:代码:

#include <iostream>
#include <cstring>
#include <stack>
#include <cstdlib>
using namespace std;

int isOperator(char x)
{
    return (x == '-' || x == '+' || x == '/' || x == '*');
}

int precedenceOfOperators(char x)
{
    if (x == '+' || x == '-')
    {
        return 1;
    }
    else if (x == '/' || x == '*')
    {
        return 2;
    }

    return 0;
}

char *infixToPostfix(char infix[])
{
    int i = 0, j = 0;
    stack<char> lobby;
    char *postfix = (char *)malloc((strlen(infix + 1)) * sizeof(char));
    while (infix[i] != '\0')
    {
        if (!isOperator(infix[i]))
        {
            postfix[j] = infix[i];
            i++;
            j++;
        }
        else
        {
            if (!lobby.empty())
            {
                if (precedenceOfOperators(infix[i]) > precedenceOfOperators(lobby.top()))
                {
                    lobby.push(infix[i]);
                }
                else
                {
                    postfix[j] = lobby.top();
                    lobby.pop();
                    j++;
                }
            }
            else if (lobby.empty())
            {
                lobby.push(infix[i]);
            }
        }
    }
    while (!lobby.empty())
    {
        postfix[j] = lobby.top();
        lobby.pop();
        j++;
    }
    return postfix;
}

Implementation:执行:

int main()
{
    char infix[] = {'a', '-', 'b', '+', 'c', '*', 'd'};
    char *postfix = infixToPostfix(infix);
    for (int j = 0; postfix[j] != '\0'; j++)
    {
        cout << postfix[j];
    }
    return 0;
}

Logic:逻辑:

  1. I created a character pointer variable that will hold our postfix expression.我创建了一个字符指针变量来保存我们的后缀表达式。 Now, we iterate over our infix expression.现在,我们遍历我们的中缀表达式。 If we receive an operand, we concatenate it to the postfix variable.如果我们收到一个操作数,我们将它连接到后缀变量。 Else if we encounter an operator, we proceed with the following steps:否则,如果遇到运算符,我们将继续执行以下步骤:
  • Keep in account the operator and its relative precedence ('/' and '*' have more precedence than '+' and '-').考虑运算符及其相对优先级('/' 和 '*' 比 '+' 和 '-' 具有更高的优先级)。
  • If either the stack is empty or its topmost operator has lower relative precedence, push this operator-precedence pair inside the stack 'lobby'.如果堆栈为空或其最上面的运算符具有较低的相对优先级,则将此运算符-优先级对推入堆栈“大厅”。
  • Else, keep popping operators from the stack 'lobby' and concatenate them to the postfix expression until the topmost operator becomes weaker in precedence relative to the current operator.否则,继续从堆栈“大厅”弹出运算符并将它们连接到后缀表达式,直到最顶层的运算符相对于当前运算符的优先级变得更弱。
  1. If you reach the EOE, pop every element from the stack 'lobby', if there is any, and concatenate them as well to the postfix expression.如果到达 EOE,则从堆栈“大厅”中弹出每个元素(如果有),并将它们也连接到后缀表达式。

Your code is exceeding the time limit because it is stuck in the infinite loop.您的代码超过了时间限制,因为它陷入了无限循环。 You have not updated the i variable - which is the index of the infix array in the else part of the loop ie when infix[i] is an operator.您尚未更新i variable - 它是循环的 else 部分中的中缀数组的索引,即当infix[i]是运算符时。 ie in this part of the code即在这部分代码中

else
        {
            if (!lobby.empty())
            {
                if (precedenceOfOperators(infix[i]) > precedenceOfOperators(lobby.top()))
                {
                    lobby.push(infix[i]);
                }
                else
                {
                    postfix[j] = lobby.top();
                    lobby.pop();
                    j++;
                }
            }
            else if (lobby.empty())
            {
                lobby.push(infix[i]);
            }
        }

Here is the updated code which is giving perfect output.这是提供完美输出的更新代码。 ( I have made some minor changes as per my convenience, you can keep the code the same and add the i++ in the else part) (我根据自己的方便做了一些小改动,你可以保持代码不变并在 else 部分添加i++

#include <iostream>
#include <cstring>
#include <stack>
#include <cstdlib>
using namespace std;

int isOperator(char x)
{
    return (x == '-' || x == '+' || x == '/' || x == '*');
}

int precedenceOfOperators(char x)
{
    if (x == '+' || x == '-')
    {
        return 1;
    }
    else if (x == '/' || x == '*')
    {
        return 2;
    }

    return 0;
}

string infixToPostfix(char infix[])
{
    int i = 0, j = 0;
    if(sizeof(infix)==0)
    {
        return "";
    }
    int n=sizeof(infix)/sizeof(infix[0]);
    stack<char> lobby;
    string postfix = "";
    while (i < n)
    {
        if (!isOperator(infix[i]))
        {   postfix=postfix+infix[i];
            i++;
            j++;
        }
        else
        {
            if (!lobby.empty())
            {
                if (precedenceOfOperators(infix[i]) > precedenceOfOperators(lobby.top()))
                {
                    lobby.push(infix[i]);
                }
                else
                {
                    postfix = postfix+lobby.top();
                    lobby.pop();
                    j++;
                }
            }
            else if (lobby.empty())
            {
                lobby.push(infix[i]);
            }
            i++;
        }
    }
    while (lobby.empty()==false)
    {
        postfix = postfix+lobby.top();
        lobby.pop();
        j++;
    }
    return postfix;
}
int main()
{
    char infix[] = {'a', '-', 'b', '+', 'c', '*', 'd'};
    string postfix = infixToPostfix(infix);
    for (int j = 0; j < postfix.size() ; j++)
    {
        cout << postfix[j];
    }
    return 0;
}
  • After going through my code again I found some other logical errors too.再次浏览我的代码后,我也发现了一些其他逻辑错误。 I have found a better way and have restructured the else part of while loop of function infixToPostfix() .我找到了一种更好的方法,并重组了函数infixToPostfix()的 while 循环的 else 部分。
  • And rather than taking the Infix expression as a character array, I have taken it as a string and similarly Postfix expression is also considered as a string.而不是将中缀表达式视为字符数组,而是将其视为字符串,类似地,后缀表达式也被视为字符串。

Updated infixToPostfix() :更新infixToPostfix()

string infixToPostfix(string infix)
{
    int i = 0;
    stack<char> lobby;
    string postfix;
    if (infix.size() == 0)
    {
        return "";
    }
    while (infix[i] != '\0')
    {
        if (!isOperator(infix[i]))
        {
            postfix = postfix + infix[i];
            i++;
        }
        else
        {
            while (!lobby.empty() && precedenceOperator(infix[i]) <= precedenceOperator(lobby.top()))
            {
                postfix += lobby.top();
                lobby.pop();
            }
            lobby.push(infix[i]);
            i++;
        }
    }
    while (!lobby.empty())
    {
        postfix = postfix + lobby.top();
        lobby.pop();
    }
    return postfix;
}
  • And as mentioned in other answers, i variable should also be updated in the else part of the while loop.正如其他答案中所提到的, i variable也应该在 while 循环的 else 部分中更新。

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

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