簡體   English   中英

我需要刪除單鏈表中動態分配的 object 嗎?

[英]Do I need to delete a dynamically allocated object in Singly Linked List?

我目前正在學習鏈接列表,並使用 Append 和 Prepend 方法實現了一個單鏈表,其中我使用“new”運算符在堆上分配了 Node 類型的對象。 我是否需要使用“刪除”在堆上釋放 object,如果需要,我該怎么做? 這是我的代碼:-

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;
    }

next不初始化數據成員。 因此成員函數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具有不確定的值。

您可以更簡單地聲明 class Node ,例如

struct Node
{
    int data;
    Node* next;
};

Node* head = nullptr;

在這種情況下,例如Prepend Prepend 看起來像

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

構造函數看起來像

List() = default;

要釋放列表中所有已分配的節點,您可以再編寫兩個成員函數clear和調用 function clear的析構函數。

例如

#include <functional>

//...

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

    ~List() { clear(); }
    //...

此外,您至少應該編寫一個復制構造函數和復制賦值運算符或將它們定義為已刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM