Empty a linked-list object

Viewed 58

I have my linked list code:

#include <string>
#include <iostream>
using namespace std;

class Node
{
public:
    string name;
    int age;
    Node *next;
    Node(string name, int age)
    {
        this->name = name;
        this->age = age;
        this->next = nullptr;
    }
};

class List
{
private:
    Node *head;
    int size;

public:
    List()
    {
        this->head = nullptr;
        this->size = 0;
    }

    void insert(string name, int age)
    {
        Node *nodenew = new Node(name, age);
        nodenew->next = nullptr;
        if (this->head == nullptr)
        {
            this->head = nodenew;
        }
        else
        {
            Node *auxi = this->head;
            while (auxi->next != nullptr)
            {
                auxi = auxi->next;
            }
            auxi->next = nodenew;
        }
        this->size = this->size + 1;
    }

    void print()
    {
        if (this->head == nullptr)
        {
            cout << "List is empty"<<endl;
        }

        Node *auxi = this->head;
        cout<<to_string(this->size)+" users in the linked list"<<endl;

        while (auxi != nullptr)
        {

            cout << auxi->name << ", " << auxi->age << endl;
            auxi = auxi->next;
        }
    }
};

int main()
{
    List linkedList;
    
    linkedList.insert("David", 56);
    linkedList.insert("Susan", 25);
    linkedList.insert("Kim", 41);
    linkedList.insert("Charles", 23);
    linkedList.insert("Bob", 20);
    linkedList.insert("James", 75);
    linkedList.insert("Carl", 36);
    linkedList.insert("Andy", 78);
    linkedList.print();
    return 0;
}

As you can see I did insert method, print method. And now want I want is to delete all nodes in the linkedList object, so I would like to know if there is some way to make for example something like linkedList = nullptr or something similar to delete all data in my linked list.

I tried to make that in the main method:

linkedList = nullptr;

But my compiler shows me this error:

no operator "=" matches these operands

I hope you can help me, thanks.

1 Answers

linkedList = nullptr; won't work, since it makes no sense. linkedList isn't a pointer. It has a pointer inside of it, but it's not itself a pointer. Besides, if that did work, it wouldn't delete the nodes, so it would be a memory leak.

You should create a function empty() (or more usually called clear()) in your List class. Make it so it deletes all the nodes, then sets head to nullptr and size to 0. Then in main(), you can call linkedList.empty(); (or linkedList.clear();)

Related