【问题标题】:converting from postfix to infix using stacks使用堆栈从后缀转换为中缀
【发布时间】:2015-09-12 17:09:58
【问题描述】:

我目前正在做一个项目,使用链表形式的堆栈从后缀转换为中缀。我目前正在尝试将整行作为字符串读取,然后将其放入字符数组中,然后当发现符号时,将一个元素放入右操作数中,将另一个元素放入左操作数中,然后将其打印回来,包括运算符。但是,在将第一项放入左侧操作数然后弹出堆栈后,我无法将另一项放入右侧操作数中。可能是什么问题呢?我用我的流行功能。

这是我的代码:

#include "stack.h"

stack::~stack()
{
    cout<<"Inside !stack \n";
    while(s_top != 0)
    {
        pop();
    }
}

void stack::pop()
{
    cout<<"Inside pop \n";
    stack_node *p;

    if (s_top != 0)
    {
        p = s_top;
        s_top = s_top->next;
        delete p;
    }

}

void stack::push(char a)
{
    cout<<"Inside push \n";
    stack_node *p = new stack_node;

    p->data = a;
    p->next = s_top;
    s_top = p;
}

void stack::print()
{
    cout<<"Inside print \n";

    for(stack_node *p = s_top; p!=0; p=p->next)
    {
        cout<<p->data<<endl;
    }
}

stack_element stack::top()
{
    cout<<"Inside top \n";

    if (s_top == 0)
    {
        exit(1);
    }
    else
    {
        return s_top->data;
    }
}

/*stack::stack(const stack & Org)
{
    cout<<"Inside the Copy Constructor\n";
    stack_node *p=Org.s_top;

    (*this).s_top = 0;

    while(p!=0)
    {
        (*this).push(p->data);
        p=p->next;  
    }
}

这是我的cpp,它不能完全工作

#include "stack.h"

string convert(string expression){

stack c;

string post = " ";
string rightop="";
string leftop="";
string op =" ";

for (int i =0; i<expression.length();i++){
c.push(expression[i]);

if(expression[i]=='*'||'+'||'-'||'/'){
cout<<c.top()<<endl;
leftop=c.top();


c.pop();


rightop=c.top();
cout<<rightop<<endl;
c.pop();
op=c.top();

c.pop();
}
}

}



int main(){

string expression;
cout<<" Enter a Post Fix expression: ";

getline(cin,expression);

convert(expression);

return 0;

}

【问题讨论】:

    标签: c++ linked-list stack postfix-notation infix-notation


    【解决方案1】:

    这里有个问题:
    (expression[i]=='*'||'+'||'-'||'/'
    这并不像你认为的那样。

    修复:

    (expression[i] == '*' ||
      expression[i] == '+' ||
      expression[i] == '-' ||
      expression[i] == '/')
    

    编辑 1:搜索字符串
    另一种方法是:

    char c = expression[i];
    const std::string operators="*+-/";
    if (operators.find(c) != std::string::npos)
    {
      // expression[i] is an operator character
    }
    

    一般贴出的解决方案是使用switch

    switch (expression[i])
    {
      case '+':  Process_Operator_Plus(); break;
      case '-':  Process_Operator_Minus(); break;
      case '*':  Process_Operator_Multiply(); break;
      case '/':  Process_Operator_Divide(); break;
    }
    

    请记住,在评估表达式时,您需要处理运算符优先级。

    【讨论】:

    • 谢谢,但这并没有解决问题。我不确定,但我认为问题出在我的 pop 方法和堆栈上
    • 我找到了问题,感谢您的回答
    猜你喜欢
    • 2015-09-13
    • 2013-11-08
    • 2013-03-28
    • 2012-09-22
    • 2015-04-19
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    相关资源
    最近更新 更多