在C++中实现链表时的运行时(或逻辑)错误

runtime ( or maybe logical ) error when implementing linked list in c++

本文关键字:错误 运行时 C++ 实现 链表      更新时间:2023-10-16

链表是一种线性数据结构,其中每个元素都是一个单独的对象。列表的每个元素(我们称之为节点)都由两个项目组成 - 数据和对下一个节点的引用。最后一个节点具有对 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;
}

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

this->last->next=new_node;

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

我没有

分析列表实现,但也许这很重要:list->insert(1, string("asd"));