user13245776
user13245776

Reputation:

Linked List destructor without head?

I'm stuck on a linked list destructor for my class. This is what I have here:

LinkedList::~LinkedList()
{
    LinkedList *forward = nullptr;
    LinkedList *current = this;
    //iterate through list, deleting each element as we go
    while (current != nullptr)
    {
            //set next pointer to current's next
            forward = current->next;
            delete current; //delete the current memory
            current = forward; //reset current to next's pointer
    }
}

When I run it, I get a seg fault. I only want to delete just one node from my linked list. Is that possible? Also, I wasn't given a "head" pointer as I was used to from other lists, so I used "this" instead, does that work?

Aka - the .cpp is finding the spot in the linked list to delete, reorganizing the next pointers around it, and then deleting the node (which calls this destructor)

(when I run my program with an empty destructor, it prints out fine, but of course there are memory leaks)

Any help is appreciated!

Upvotes: 0

Views: 430

Answers (2)

bruno
bruno

Reputation: 32596

by definition delete calls LinkedList::~LinkedList, so you have several (in fact infinite) calls to it because of the loop calling delete, so you access to already deleted element with an undefined behavior

just do

LinkedList::~LinkedList()
{
   if (next != nullptr)
     delete next;
}

or just

LinkedList::~LinkedList()
{
   delete next; // delete on nullptr does nothing
}

even personally I prefer to compare to nullptr first

Upvotes: 3

victor12369
victor12369

Reputation: 153

I argee with bruno.

Besides, when you want to delete a node and you don't have the pointer to head, you need a double-linked list.

The double-linked list has two pointers to its prev and next node.

when you need to delete a node, like this:

ListNode* p;
if(p->pre)
    p->pre->nxt = p->nxt;
if(p->nxt)
    p->nxt->pre = p->pre;
p->nxt = p->pre = NULL;
delete p;

Upvotes: 0

Related Questions