当我尝试使用此语句时:tail->prev = newElement
;
然后整个程序就关闭了。我真的很想知道为什么。
struct LinkedList{
string var_name;
string scope_name;
int scope; // 0 = global, 1 = public, 2 = private, 3 = ?
LinkedList* next = NULL;
LinkedList* prev = NULL;
};
struct LinkedList* head;
struct LinkedList* tail; //I made this two global
void insert(LinkedList* &head, LinkedList* &newElement, LinkedList* &tail){
newElement->next =NULL;
if(!head){
head = newElement;
return;
}
else{
LinkedList* last = head;
while(last->next != NULL){
last=last->next;
}
last->next = newElement;
newElement->prev = last;
tail = newElement;
tail = newElement->next;
tail->prev = newElement;
}
}
void LexicalAnalyzer:: var_list(){
LinkedList* new_node = new LinkedList[sizeof(LinkedList)];
GetToken();
new_node->var_name = tmp.lexeme;
new_node->scope_name = currentScope;
if(currentScope == "global")
new_node->scope = 0;
else if(pubOrPri == 1)
new_node->scope = 1;
else if(pubOrPri == 2)
new_node->scope = 2;
insert(head, new_node, tail);
//tail->prev = new_node;
display();
if(tmp.token_type == ID){
GetToken();
if(tmp.token_type == COMMA)
var_list();
else if(tmp.token_type == SEMICOLON){
return;
}
else
syntaxError();
}
else
syntaxError();
}
输出给了我
Process returned -1073741819 (0xC0000005) execution time : 3.269 s.
但是如果我删除tail->newElement;
,并且把函数中的参数tail去掉。一切都很好。
我想,tail 是全局的,那我为什么不直接在 var_list()
函数中尝试 tail->prev = new_Node;
呢?工作也一样。
最佳答案
您没有任何逻辑来处理 tail
的初始状态,即 nullptr
。
改变
if(!head){
head = newElement;
return;
}
到
if(!head){
head = tail = newElement;
return;
}
此外,行
tail->prev = newElement;
需要
tail = newElement;
在 else
block 中。
免责声明我没有测试该建议是否解决了问题。
关于c++ - 如何在列表末尾添加尾元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57333440/