创建简单链接列表时无法访问内存

时间:2015-02-26 18:49:55

标签: c++ constructor linked-list

我只是想制作一个非常简单的链表,但由于某种原因,我得到一个"无法访问内存"错误。我已经构建了所有其他方法,但我实际上无法创建第一个节点。语言是C ++。

构造函数如下所示:

IntListNode::IntListNode(){
    data = -1;
    next = this;
    prev = this;
}

Linked List构造函数如下所示:

IntList::IntList(){
    IntListNode* sentinel = new IntListNode(); 
}

有人能看到问题吗?感谢。

2 个答案:

答案 0 :(得分:1)

此构造函数

IntList::IntList(){
    IntListNode* sentinel = new IntListNode(); 
}

毫无意义。声明的局部变量sentinel将在退出构造函数后立即销毁。

这个构造函数

IntListNode::IntListNode(){
    data = -1;
    next = this;
    prev = this;
}

非常混乱。最好不要明确声明构造函数并简单地使用聚合。或者至少构造函数看起来像

IntListNode( int value, 
             IntListNode *next = nullptr, 
             IntListNode *prev = nullptr  ) 
                : data( value ), next( next ), prev( prev )
{
}

我认为数据类型为int。

拥有一个哨兵节点是没有意义的。您应该定义两个节点:head和tail,最初将设置为nullptr。

答案 1 :(得分:0)

您应该在概念上将链接列表拆分为两个类:

  1. 容器
  2. 节点
  3. 链接列表容器

    容器包含指向第一个节点的指针,通常称为 head ,可选地,指向最后一个节点的指针,通常称为尾部:

    class Linked_List
    {
      Node * head;
      Node * tail;
    public:
      Linked_List : head(nullptr), tail(nullptr)
      { ; }
    };
    

    链接列表节点

    节点类包含指向下一个节点的指针。在双向链表类的情况下,它包含指向前一节点的指针。

    class Node
    {
      Node * next;
      public:
        Node() : next(nullptr)
        { ; }
        void link_to(Node & other)
        {
          next = &other;
        }
        void remove_link()
        {
          next = nullptr;
        }
    };
    

    专业化节点 您可以通过以下方式专门化节点类:

    • 向班级添加数据字段
    • 包含数据字段并继承自Node
    • 的新类
    • 将其设为template课程。

    示例:

    class Integer_Node_Inheritance : public Node
    {
      public:
        int data;
    };
    
    class Node
    {
      Node * next;
      int    data;
      public:
        Node() : next(nullptr)
        { ; }
        void link_to(Node & other)
        {
          next = &other;
        }
        void remove_link()
        {
          next = nullptr;
        }
    };
    
    template <typename Data_Type>
    class Node
    {
      Node *      next;
      Data_Type   data;
      public:
        Node() : next(nullptr)
        { ; }
        void link_to(Node & other)
        {
          next = &other;
        }
        void remove_link()
        {
          next = nullptr;
        }
    };