Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ function that deletes dynamic linked list

I’m currently working on a class project where we make a linked list and we’re supposed to create a function that clears the list then deletes it (with "delete LIST_NAME;"). I have implemented the function as instructed by my professor, also forcing the list to become null after the delete. The function works within itself, but when it returns to the main function, the list gets a new value.

Is this sort of function just not possible in C++?

#include <iostream>

struct Node 
{
  int val;
  Node* next;
};

struct LinkedList
{
  int count;
  Node* head;
  Node* tail;
};

void Clear(LinkedList* list) {
  Node* node = list->head;
  Node* next = nullptr;

  while (node != nullptr) {
    next = node->next;
    delete node;
    node = next;
  }
  list->head = nullptr;
  list->tail = nullptr;
  list->count = 0;
}

void Destroy (LinkedList* list) {
  Clear(list);
  delete list;
  list = nullptr;
  std::cout << "\n(should be) Destroyed";
}

int main() {
  //creating a list element
  Node* node = new Node;
  node->val = 'a';
  node->next = nullptr;

  //inserting the element onto list
  LinkedList* list  = new LinkedList;
  list->count = 0;
  list->head = node;
  list->tail = node;

  std::cout << "\nList: " << list;

  Destroy(list);
  
  std::cout << "\nList: " << list;

  std::cout << "\nEND";
  
}

This is just a snip of my code but it shows what I mean. Using the debugger the list has the value 0x0 by the end of the function but in the main function it’s assigned a new value as shown by the debugger.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You take list by value so it’s local to the function.

If you’d like to make changes to it that are visible at the call site, take it by reference:

// `list` is now a reference to the pointer at the call site:
void Destroy(LinkedList*& list) {
    Clear(list);
    delete list;
    list = nullptr; // this now sets the referenced `LinkedList*` to `nullptr`
    std::cout << "\n(should be) Destroyed";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading