I have a linked list code in C++:
#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;
}
}
void deleteList(){//this method
Node* prev = this->head;
this->size = 0;
while (this->head)
{
this->head = head->next;
delete(prev);
prev = this->head;
}
}
};
int main()
{
List linkedList;
linkedList.insert("David", 56);
linkedList.insert("Susan", 25);
linkedList.insert("Kim", 41);
linkedList.insert("Charles", 23);
linkedList.print();
linkedList.deleteList();
//inserting data again after deleting all data in the linked list
linkedList.insert("Bob", 20);
linkedList.insert("James", 75);
linkedList.insert("Carl", 36);
linkedList.insert("Andy", 78);
linkedList.deleteList();
linkedList.print();
return 0;
}
I get in console the correct output:
4 users in the linked list
David, 56
Susan, 25
Kim, 41
Charles, 23
List is empty
0 users in the linked list
But, I think should be some way to improve my deleteList()
method. This method get empty my linked list object.
I tried to make it more efficient, but I couldn't.
I hope you can help me with that or anything more in my linked list code, thanks.