c++ - Delete list of Singly linked list -


i'm practicing data structures , i've implemented code creates singly linked list, add list , delete list. know if delete list function doing should do. think because when try print list after delete crashes. advice on ensuring deleting list or other advice may have on improving code. i'm still bit of rookie when comes dynamically allocating memory.

typedef struct node {     int data;     node* next; }* nodeptr;  nodeptr addtolist(nodeptr head, int data) {     nodeptr newitem = new node; //create new item       newitem->data = data; //assign data new item      newitem->next = head; //point head      return newitem; //return new head }  void deletelist(nodeptr head) {     if (head == nullptr) {         return;     }     else {         deletelist(head->next);         delete head;         head = nullptr;     } }  void print(nodeptr n) {     while (n != nullptr) {         cout << n->data << " ";         n = n->next;     } }  int main() {     nodeptr head = new node;     nodeptr second = new node;     nodeptr third = new node;      head->data = 1;     head->next = second;      second->data = 2;     second->next = third;      third->data = 3;     third->next = nullptr;      print(head);     cout << endl;      head = addtolist(head, 0);      print(head);     cout << endl;      deletelist(head);      return 0; } 

when call:

deletelist(head); 

head won't equal null after statement. instead, you'll need like:

deletelist(head); head = null; 

or:

void deletelist(nodeptr & head) {     if (head == nullptr) {         return;     }     else {         deletelist(head->next);         delete head;         head = nullptr;     } } 

note use reference parameter deletelist.


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -