基于节点的链表的参数化构造函数

问题描述 投票:1回答:1

我在CS2,我们只是学习链表,我必须编写链表类的参数化构造函数(基于节点)。我真的不了解节点列表,所以对这里发生的事情或如何处理的任何帮助都会有所帮助!我给出了以下Node类:

class Node {

friend class NodeList;

public:
 Node() : m_next(NULL) {}
 Node(const DataType& data, Node* next = NULL) :
        m_next(next), m_data(data) {}
 Node(const Node& other) : m_next(other.m_next),
                           m_data(other.m_data) {}

 DataType& data() { return m_data; }

 const DataType& data() const { return m_data; }

private:
 Node* m_next;
 DataType m_data;
};

我正在尝试为以下类创建参数化构造函数:

Class NodeList {
    public:
     NodeList();
     NodeList(size_t count, const int value);
    private:
     Node* m_head;
}

,参数化构造函数应该将'count'节点初始化为'value'。

谢谢!

c++ linked-list nodes
1个回答
1
投票

解决这样的问题有3个部分。

  • 将问题分解为更简单,更简单的任务,使其更容易解决
  • 做较小的任务
  • 用它们来解决这个大问题。

什么能让你轻松解决这个问题?向列表中添加一个值比向列表中添加多个值更容易,所以让我们编写一个函数来执行此操作。

要在列表的开头添加一个值,

  • 我们可以使用该值创建一个新节点
  • 我们将新节点指向当前的第一个节点
  • 我们将当前的第一个节点设置为新节点。

让我们调用我们的函数prepend,因为它将值添加到列表中。

class NodeList {
   public:
    // The head should be set to null initially
    NodeList() 
      : m_head(nullptr) 
    {
    }
    // This function takes a value and adds it to the beginning of the list
    void prepend(const DataType& value) {
        // The new node uses the current head as the next value
        Node* newNode = new Node(value, m_head); 
        // We set the current head to the new node. 
        m_head = newNode; 
    }

现在,多次添加值很容易。我们可以在每次添加项目时调用prepend一次。

class NodeList {
   public:
    // The head should be set to null initially
    NodeList() 
      : m_head(nullptr) 
    {
    }
    // This function takes a value and adds it to the beginning of the list
    void prepend(const DataType& value) {
        // The new node uses the current head as the next value
        Node* newNode = new Node(value, m_head); 
        // We set the current head to the new node. 
        m_head = newNode; 
    }

    NodeList(size_t count, const DataType& value) 
      : m_head(nullptr) // The head still has to be null initially
    {
        for(size_t i = 0; i < count; i++) 
        {
           prepend(value); 
        }
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.