c++ - 如何在列表末尾添加尾元素

标签 c++ doubly-linked-list

当我尝试使用此语句时: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/

相关文章:

c++ - 抽象基类定义

无法在双向链表中从尾部遍历到头部

java - BinarySearchingTree - dll(generic),不知何故我的项目无法添加到我的 adt 中

c++ - 在堆上分配时,在哪些情况下会发生 "automatic"清理(如果有的话),在哪些情况下不会发生?

c++ - 标准 C++ 库文件夹中的元组文件已损坏。如何修改?

c++ - 如何使用数组指针?

c++ - 链表搜索函数修改列表

java - 使用 self 作为参数创建实例

algorithm - 什么抽象数据类型 (ADT) 用于在 Python 中实现 steinhaus-johnson-trotter(排列)算法?

c++ - 在 Xcode 中设置 Lua 时遇到问题