在c ++中实现链表时的运行时(或可能是逻辑)错误

时间:2016-01-15 11:16:04

标签: c++ data-structures linked-list singly-linked-list

链表是一种线性数据结构,其中每个元素都是一个单独的对象。列表的每个元素(我们将其称为节点)包括两个项目 - 数据和对下一个节点的引用。最后一个节点引用null 所以我试图在c ++中创建一个简单的链表(不是双重或循环),这是我的代码。我使用xcode运行它,语法没有问题。我添加了一个带有键1和数据" asd"的节点。我试图打印列表的元素,但我看到的是:(lldb)
问题是什么?
提前致谢。

#include <iostream>
#include <string>
using namespace std;
class node {
    friend class linkedlist;
private:
    int key;
    string data;
    node *next;
public:
    node(int k,string d){
        this->key=k;
        this->data=d;
    }

};
class linkedlist{
private:
    node *head;
    node *last;
public:
    linkedlist(){
        this->head=NULL;
        this->last=NULL;
    }
    inline bool is_empty() {return head==NULL;}
    void print(){
        cout<<"\n";
        node *current;
        for(current=this->head;current!=NULL;current=current->next){
            cout<<"("<<current->key<<","<<current->data<<")"<<" ";
        }
        cout<<"\n";
    }
    void insert(int k,string d){
        node *new_node=new node(k,d);
        this->last->next=new_node;
        this->last=new_node;
        if(this->is_empty()) this->head=new_node;
    }
};


int main()
{
    linkedlist *list=new linkedlist();
    list->insert(1,"asd");
    list->print();
    return 0;
}

2 个答案:

答案 0 :(得分:0)

我没有分析列表实现,但这可能主要是:KeyManager

答案 1 :(得分:0)

insert函数中,您尝试访问NULL对象:

this->last->next=new_node;

您的列表为空,即headlast为空。