[英]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 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;
}
這里有一個問題:
(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;
}
請記住,在評估表達式時您需要處理運算符優先級。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.