我需要删除Singly Linked List中动态分配的对象吗



我目前正在学习链表,并使用Append和Prepend方法实现了一个单链表,其中我使用"new"运算符在堆上分配了Node类型的对象。我需要使用"delete"来释放堆上的对象吗?如果需要,我该怎么做?这是我的代码:-

class List
{
private:
class Node
{
public:
int data;
Node* next;
Node()
{
data = 0;
next = NULL;
}
Node(const int& data)
{
this->data = data;
}
};
Node* head;
public:
List()
{
head = NULL;
}
void Append(const int&val);
void Prepend(const int&val);
void DisplayAll();
};
void List::Append(const int&val)
{
Node* n = new Node(val); //dynamically allocated 
if (head == NULL)
{
head = n;
return;
}
Node* temp = NULL;
temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = n;
}
void List::Prepend(const int&val)
{
Node* node = new Node(val);//dynamically allocated 
if (head == NULL)
{
head = node;
return;
}
node->next = head;
head = node;
}
void List::DisplayAll()
{
Node* temp = head;
while (temp != NULL)
{
std::cout << temp->data << ' ';
temp = temp->next;
}
}

对于初学者来说,这个构造函数

Node(const int& data)
{
this->data = data;
}

不初始化数据成员CCD_ 1。因此,成员函数AppendPrepend具有错误

void List::Append(const int&val)
{
Node* n = new Node(val); //dynamically allocated 
if (head == NULL)
{
head = n;
return;
}
//...

void List::Prepend(const int&val)
{
Node* node = new Node(val);//dynamically allocated 
if (head == NULL)
{
head = node;
return;
}
//...

头节点的数据成员next具有不确定的值。

您可以像一样简单地声明类Node

struct Node
{
int data;
Node* next;
};
Node* head = nullptr;

例如,在这种情况下,函数Prepend将看起来像

void List::Prepend( const int &val )
{
head = new Node { val, head };
}

构造函数将看起来像

List() = default;

要释放列表中所有已分配的节点,可以再编写两个成员函数clear和调用函数clear的析构函数。

例如

#include <functional>
//...
class List
{
//...
public:
void clear()
{
while ( head ) delete std::exchange( head, head->next );
}
~List() { clear(); }
//...

此外,您至少应该编写一个复制构造函数和复制赋值运算符,或者将它们定义为已删除。

最新更新