首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基于节点链表的参数化构造器

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

Stack Overflow用户
提问于 2019-04-19 03:59:47
回答 1查看 519关注 0票数 1

我在CS2,我们只是学习链接列表,我必须编写一个链表类(基于节点)的参数化构造函数。我不太明白节点列表,所以对这里发生了什么或者如何处理会有帮助!我有以下的Node课程:

代码语言:javascript
运行
复制
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;
};

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

代码语言:javascript
运行
复制
Class NodeList {
    public:
     NodeList();
     NodeList(size_t count, const int value);
    private:
     Node* m_head;
}

,其中参数化构造函数应该将“count”节点初始化为“value”。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-19 05:25:18

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

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

如何更容易地解决这个问题?向列表中添加一个值要比向列表中添加多个值容易得多,所以让我们编写一个函数来完成这个任务。

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

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

让我们调用我们的函数prepend,因为它将值放在列表的前面。

代码语言:javascript
运行
复制
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一次。

代码语言:javascript
运行
复制
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); 
        }
    }
};
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55756420

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档