I have actually a linked_list and currently mine destructor is not working properly. Not entirely sure why.Can somebody explain me how to fix this?

class linked_list { private:struct node // cable in this node std::string data; // tip to following node struct node *next;;//First item in the liststruct node *first;Here is mine destructor

linked_list::~linked_list(void)while (first) delete first; very first = first->next;


You are watching: Destructor for linked list c++

*

*

The trouble lies here:

delete first;first = first->next;When girlfriend delete first, yet then shot to accessibility first->next. Cache first->next into a temp change of form node*, then do delete very first to deal with this:

struct node* temp;while (first != NULL) temp = first->next; delete first; very first = temp;

*

change to

linked_list::~linked_list(void)struct node *next;while (first != NULL) next = first->next; delete first; first = next;

*

When girlfriend "delete" first, you actually clear all the links from it. Now, if you try to accessibility some other node making use of this, will not develop the compelled result.

First, you have actually to suggest that node v some various other pointer, so the you still have actually some connect which you can accessibility later.


*

Thanks because that contributing an answer to ridge Overflow!

Please be sure to answer the question. Provide details and also share her research!

But avoid

Asking for help, clarification, or responding to various other answers.Making statements based on opinion; ago them up with references or an individual experience.

To discover more, see our advice on writing great answers.


article Your answer Discard

By clicking “Post your Answer”, friend agree come our terms of service, privacy policy and also cookie policy


Not the prize you're looking for? Browse other questions tagged c++ linked-list destructor or asking your own question.




See more: Into The Spider Man Into The Spider Verse Hoodie S, Into The Spider

site architecture / logo © 2021 ridge Exchange Inc; user contributions licensed under cc by-sa. Rev2021.10.8.40416


your privacy

By clicking “Accept every cookies”, friend agree stack Exchange can store cookies on your an equipment and disclose details in accordance through our Cookie Policy.