Why is my destructor causing an issue with my linked list

my destructor:

~list() {
    for (node *p; !isEmpty();) 
    {
        p = head->next;
        delete head;
        head = p;
    }
}

My function append:

void append( list L2)
{

    if (head == 0 && L2.head == 0)
    {
        cout << "Error List Empty" << endl;



    }
    else if (isEmpty())
    {
            L2.printAll();
    }
    else if (L2.isEmpty())
    {
            printAll();  
    }


    else
    {
        tail->next = L2.head;
        tail = L2.tail;
        L2.head = L2.tail = 0;
    }
}

The code stops when the destructor tries to run.

My main:

int main()
{
list l1;
l1.addToHead(1);
l1.addToHead(2);

list l2;
l2.addToHead(9);
l2.addToHead(3);
l2.addToHead(4);

l1.printAll();

cout << "-------------------" << endl;
l2.printAll();

l1.append(l2);

cout << "=============" << endl;

output: 2 1 line of slashes 4 3 9 line of equals press any key to continue...

When I did not account for the other conditions like if l1 is empty or l2 is empty, the code worked fine. It appended l2 to l1, and emptied l2.

But now that I'm trying to account for both lists being empty or one list being empty, I'm getting a debug assertion. It looks like the destructor tries to run, then runs into a problem right before "delete head"

UPDATE--

the isEmpty fn:

    int isEmpty() {
    return head == 0;
}

Answers


My bet is that isEmpty is checking if head is NULL or not, which is always evaluating to true because you never set it otherwise.

Try this instead:

node* p = NULL;

while (head != NULL)
{
    p = head->next;
    delete head;
    head = p;
}

I think the return type of isEmpty() should be boolean

bool isEmpty() {
    return head == 0;
 }

Need Your Help

Event dispatching library with IoC

c# events nuget inversion-of-control

In the past I've built a MessageDispatcher component that scans an assembly for types decorated with certain attributes and initializes an instance of each. Then, when any object is fed to the

Python - How can I read input from a device using ioctl or spidev?

python c ioctl spi

I have a hardware device and the vendor that supplied it gave a bit of C code to listen for button presses which uses ioctl. The device has an SSD1289 controller.