我在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”。
谢谢!
发布于 2019-04-19 05:25:18
解决像这样的问题有三个部分。
如何更容易地解决这个问题?向列表中添加一个值要比向列表中添加多个值容易得多,所以让我们编写一个函数来完成这个任务。
若要在列表开头添加一个值,
让我们调用我们的函数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);
}
}
};https://stackoverflow.com/questions/55756420
复制相似问题