【问题标题】:Can't access memory when creating simple linked list创建简单链表时无法访问内存
【发布时间】:2015-04-29 07:11:34
【问题描述】:

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

构造函数如下所示:

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

Linked List 构造函数如下所示:

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

任何人都可以看到问题吗?谢谢。

【问题讨论】:

  • 如果您指定这是什么语言会很有帮助。
  • 语言是C++。
  • 看起来您的“第一个节点”是 IntList 构造函数中的一个局部变量,但您没有显示足够的代码来确定。

标签: c++ constructor linked-list


【解决方案1】:

你应该在概念上将你的链表分成两个类:

  1. 容器
  2. 节点

链表容器

容器包含一个指向第一个节点的指针,通常称为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;
    }
};

【讨论】:

    【解决方案2】:

    这个构造函数

    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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-14
      • 2011-10-02
      • 2023-04-02
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多