使用堆栈从后缀转换为中缀
converting from postfix to infix using stacks
我目前正在进行一个项目,使用链表形式的堆栈将后缀转换为中缀。我目前正试图将整行作为字符串读取,然后将其放入字符数组中,然后当找到符号时,将一个元素放入右操作数,另一个元素置于左操作数,然后通过运算符将其打印出来。然而,在将第一项放入左操作数,然后弹出堆栈之后,我无法将另一项放入右操作数。可能是什么问题?我喜欢我的流行音乐。
这是我的代码:
#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 Constructorn";
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;
}
这里有一个问题:(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;
}
请记住,在计算表达式时需要处理运算符优先级。
相关文章:
- 使用带有链表的堆栈数据结构将中缀转换为后缀
- 中缀后缀转换C ++,似乎无法得到正确的答案
- n-ary布尔语法从中缀到前缀的Boost::Spirit转换?
- 使用 C++ 将中缀转换为后缀(包括赋值运算符)
- 中缀到 C++ 中的后缀转换
- 使用堆栈的后缀转换器中缀
- 将中缀转换为后缀并获取分段错误核心转储错误
- 中缀到后缀表达式转换代码不起作用
- 使用Stacks从中缀表达式转换为后缀(C++)
- 将中缀转换为后固定N位数的计算
- 将中缀转换为后缀:无法识别堆栈错误
- 将中缀转换为后缀表示法
- 这个后缀转换 C++ 代码的中缀有什么问题
- 中缀到后缀转换器 + 评估程序正确打印到控制台,但不正确地打印到文本文件
- 将中缀转换为中缀
- 中缀到后缀转换括号错误
- 使用链表将中缀转换为后缀时出错
- 中缀到后缀代码转换
- C++正在将Postfix转换为中缀
- 是否有C/C++库来转换MathML<->中缀?