添加元素后链接列表程序崩溃

时间:2017-03-15 12:37:08

标签: c++ list linked-list

我的程序在插入头部序列后崩溃,然后插入尾部,其他所有情况似乎都有效。我无法弄明白。

struct Node {
    int key;
    Node *next;
};

struct List {
    Node *head, *tail;
};

void init(List& l) {
    l.head = l.tail = NULL;
}

void insertHead(List& l, int x) {
    Node *temp=new Node;
    temp->next=NULL;
    temp->key=x;
    temp->next=l.head;
    l.head=temp;
}

void insertTail(List& l, int x) {
    Node *temp=new Node;
    temp->key=x;
    temp->next=NULL;
    if(l.head==NULL) {
        l.head = temp;
        l.tail = temp;
    } else {
        l.tail->next=temp;
        l.tail=temp;
    }
}

这只是我代码的一部分,但我认为这已经足够了,否则这里只剩下部分http://pastebin.com/WxmYJ0uE

1 个答案:

答案 0 :(得分:2)

当插入列表中的第一个元素时,您忘记设置尾部。

void insertHead(List& l, int x) {
    Node *temp=new Node;
    temp->next=NULL;
    temp->key=x;
    temp->next=l.head;
    l.head=temp;

    if(l.tail == NULL) l.tail = l.head; // <-- you forgot this
}
相关问题