如何在列表末尾添加尾元素

时间:2019-08-02 21:06:44

标签: 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();
}

输出给了我

  

进程返回的-1073741819(0xC0000005)执行时间:3.269 s。

但是,如果我删除tail-> newElement;并删除函数中的参数tail。一切都很好。

我认为,tail是全局的,那为什么我为什么不直接在tail->prev = new_Node;函数中尝试var_list()呢?

2 个答案:

答案 0 :(得分:1)

您没有任何逻辑可以处理tail的初始状态,即nullptr

更改

if(!head){
    head = newElement;
    return;
}

if(!head){
    head = tail = newElement;
    return;
}

此外,该行

    tail->prev = newElement;

需要成为

    tail = newElement;

else块中。

免责声明,我尚未测试该建议是否可以解决问题。

答案 1 :(得分:0)

尝试这种逻辑,

void insert(LinkedList* &head, LinkedList* &newElement, LinkedList* &tail){
        newElement->next =NULL;

        if(!head){
                head = tail = newElement; // your first node is both head and tail;
                return;
        }
        else{
                LinkedList* last = head;
                while(last->next != NULL){
                        last=last->next;
                }
                last->next = newElement;
                newElement->prev = last; // newElement is inserted to end of the list
                tail = newElement; // tail is moved to last element in the list
                //tail = newElement->next;
                newElement->next = NULL; // tail of next is always NULL; end of the list
                //tail->prev = newElement;
                tail->prev = last; // tail of prev must be last 
        }
}