使用堆栈添加到Postfix C++:错误代码6
问题描述:
我的任务是实现使用单向链表将字符串以中缀形式转换为后缀形式的堆栈。为了简单起见,该字符串不包含任何空格。使用堆栈添加到Postfix C++:错误代码6
我简而言之算法是:从缀串
读取字符创建操作
推的顺序与字符一个临时节点及其关联优先如果它是一个操作而不是一个数字/如果它是一个数字,则将它自动附加到堆栈上
每次将字符压入堆栈时,如果堆栈的顶层节点的优先级高于下一个字符的临时节点的优先级,请从堆栈中弹出并将其附加到后缀字符串中。
这些步骤在手工添加到postfix时有效。 每当我尝试运行我的代码时,我都会收到错误6 SIGABRT。我的代码应该很容易理解。任何人都可以告诉我这个错误意味着什么,为什么我得到它,以及如何解决它,以便我的代码正确地输出后缀字符串?
#include <iostream>
#include <string>
using namespace std;
string postfix; //infix and postfix strings
//function to return true if a character is an operation
bool isoperator(char a)
{
if(a == '(' || ')' || '*' || '/' || '+' || '-') //might need to
change to "" instead of ''
{
return(true);
}
else
{
return(false);
}
}
//node class
class node
{
public:
char character;
//double number;
int level; //to check for precedence of operations
node *ptr;
void assignlevel()
{
switch(character)
{
case ')':
level = 3;
break;
case '(':
level = 0;
break;
case '+':
level = 1;
break;
case '-':
level = 1;
break;
case '*':
level = 2;
break;
case '/':
level = 2;
break;
default:
level = 0;
}
}
friend class stack;
};
//stack class
class stack
{
public:
node *top, *temp;
//Constructor Function
stack()
{
top = new node;
top->character = '&';
top->ptr = NULL;
top->level = 0;
temp = new node;
temp->ptr = NULL;
}
//Empty
bool empty()
{
return(top->character == '&');
}
//Read character from string
void readchar(char a)
{
temp->character = a;
temp->assignlevel();
}
//Check Precedence of top and temp
bool precedence()
{
return(top->level >= temp->level);
}
//Push function for infix to postfix
void push1(char a)
{
readchar(a);
if(isoperator(temp->character)) //Push onto stack if character is an operation
{
if(empty())
{
top->character = temp->character;
top->assignlevel();
}
else
{
node *v = new node;
v->character = temp->character;
v->level = temp->level;
v->ptr = top;
top = v;
delete v;
}
}
else //append to string if character is number
{
postfix += temp->character;
}
if(precedence()) //we check if we have to pop every time we push
onto the stack
{
pop1();
}
}
void pop1() //Pop onto postfix string
{
postfix += top->character;
node *w = top->ptr;
delete ⊤
top = w;
delete w;
}
};
int main()
{
string infix = "2+3-5*(7+1)";
stack op;
for(int i = 0; i < infix.size(); ++i)
{
op.push1(infix[i]);
}
for(int j = 0; j < infix.size(); j++)
{
cout << postfix[j];
}
return 0;
}
答
你为什么要在推送中“删除v”?这会删除刚刚创建的节点。
是的,我意识到,过了一段时间。它摆脱了那个错误,现在我至少得到了一个字符串输出 – arnavlohe15