In the following code, I've implemented a double linked list in which each node is a structure with the following fields:
firstName, seciondName, CNP, Email;
When I call the function ptr->DeleteNODE for the fifth time to delete the last node left in the list the code is no longer running.
Deleting nodes is done from the beginning of the list.
I do not understand why ?
Can you help me ?
Code:
#include <iostream>
#include <cstring>
using namespace std;
struct Persons
{
string firstName;
string secondName;
string CNP;
string Email;
};
class NODE
{
private:
NODE *next;
NODE *previous;
public:
Persons *box = new Persons();
NODE(string firstName, string secondName, string CNP, string Email)
{
box->firstName = firstName;
box->secondName = secondName;
box->CNP = CNP;
box->Email = Email;
}
void SetNext(NODE *next)
{
this->next = next;
}
NODE* GetNext()
{
return next;
}
void SetPrevious(NODE *previous)
{
this->previous = previous;
}
NODE *GetPrevious()
{
return previous;
}
};
class DoublyLinkedList
{
private:
NODE *head;
public:
DoublyLinkedList()
{
head = NULL;
}
bool isEmpty()
{
return head == NULL;
}
void AddNODE(NODE *newNode)
{
if (isEmpty())
{
newNode->SetPrevious(NULL);
head = newNode;
}
else
{
NODE *temp = head;
while (temp->GetNext() != NULL)
temp = temp->GetNext();
temp->SetNext(newNode);
newNode->SetPrevious(temp);
}
newNode->SetNext(NULL);
}
void DeleteNODE()
{
if (isEmpty())
cout << "\n List is Empty." << endl;
NODE *temp = head;
if (head->GetNext() != NULL)
{
head = head->GetNext();
head->SetPrevious(NULL);
}
else
head = NULL;
delete temp;
}
void Print()
{
NODE *temp = head;
while (temp != NULL)
{
cout << "\n First Name : " << temp->box->firstName;
cout << "\n Second Name : " << temp->box->secondName;
cout << "\n CNP : " << temp->box->CNP;
cout << "\n Email : " << temp->box->Email;
temp = temp->GetNext();
cout << endl;
}
}
};
int main()
{
DoublyLinkedList *ptr = new DoublyLinkedList();
NODE obj1("Dragu", "Stelian", "1911226284570", "[email protected]");
NODE obj2("Dragu", "Mircea", "1891226284462", "[email protected]");
NODE obj3("David", "Adrian", "1971226284462", "[email protected]");
NODE obj4("Afrem", "Dragos", "1981246627446", "[email protected]");
NODE obj5("Sandu", "Marius", "1984225774462", "[email protected]");
ptr->AddNODE(&obj1);
ptr->AddNODE(&obj2);
ptr->AddNODE(&obj3);
ptr->AddNODE(&obj4);
ptr->AddNODE(&obj5);
ptr->Print();
ptr->DeleteNODE();
ptr->DeleteNODE();
ptr->DeleteNODE();
ptr->DeleteNODE();
ptr->DeleteNODE();
ptr->Print();
return 0;
}