I need some help. Basically, I'm learning Data structures & Algorithms, and wrote a basic singly list code, but there is a problem of a runtime exception thrown due to the list destructor (which my professor taught).
#include "list.h"
#include <iostream>
using namespace std;
list::list() : head(NULL), tail(NULL) {}
Node* list::get_head() const { return head; }
Node* list::get_tail() const { return tail; }
bool list::isEmpty() const {
if (head == NULL)
return true;
return false;
}
void list::insert_end(int value) {
Node* p = new Node(value); //p->Data = value;
if (isEmpty())
head = p;
else
tail->next = p;
tail = p;
}
list::~list() {
if (isEmpty())
return;
else
cout << "Not empty\n";
cout << "Entering ~" << endl;
Node* p = head;
Node* q = head->next;
while (p != NULL)
{
cout << "Deleting:" << p->Data << "\t\t";
if (p->next == NULL) {
cout << "NOW" << endl;
}
delete p;
p = q;
if (p != NULL)
q = q->next;
}
cout << "Leaving ~" << endl;
}
#include <iostream>
#include "list.h"
void Display_headTail(list & list) {
if (!list.isEmpty())
cout << "Head:" << list.get_head()->Data
<< "\tTail:" << list.get_tail()->Data << endl;
}
int main() {
list mylist;
mylist.insert_end(1);
mylist.insert_end(2);
mylist.insert_end(3);
mylist.insert_end(4);
mylist.insert_end(5);
mylist.Display_list();
Display_headTail(mylist);//pass by Value
}
NOTE: Display_headTail()
takes list by Value, and immediately after its destructor is called, and after that the last line of code is executed giving the error:
And in case the order of instructions changed to:
mylist.Display_list();
Display_headTail(mylist);//pass by Value
Then the following error occurs:
NOTE: The destructor is called twice (no idea why) along with the exception:
Finally, if I pass the list by reference, the program works perfectly fine.