【问题标题】:Linked-list program crashing after adding elements添加元素后链表程序崩溃
【发布时间】:2017-03-15 12:37:08
【问题描述】:

我的程序在插入头部,然后插入尾部之后崩溃,其他情况似乎都有效。我想不通。

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

【问题讨论】:

  • 似乎错误在其余部分,快速浏览并没有发现它。但是你的代码中有很多杂音,比如上面 insertHead 中的 temp->next=NULL; 行,尝试清理你的代码,这样你或任何其他人修复你的代码会容易得多。
  • 用一个空列表进行测试,insertHead,然后 insertTail。在调试器中运行它。

标签: c++ list linked-list


【解决方案1】:

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

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多