【问题标题】:runtime ( or maybe logical ) error when implementing linked list in c++在 C++ 中实现链表时出现运行时(或者可能是逻辑)错误
【发布时间】:2016-01-15 11:16:03
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    this->last->next=new_node;
    

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

    【讨论】:

    • 谢谢老兄 :) 我通过在该行的开头添加 if(!this->is_empty()) 来纠正它,现在我的程序可以正常工作了:)
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-30
      • 2020-01-03
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 2019-05-28
      相关资源
      最近更新 更多