templates - C++: Deleting a node in the middle of a singly linked list? -


here code:

template<class l> node<l>* linkedlist<l>::deletenode(l todelete) {         node<l>* current;         node<l>* trail;          if(head == null)         {                 cout << "\n\ncannot delete empty list.\n\n";         }         else         {             if(head->next == null)             {                 if(head->data == todelete)                 {                     current = head;                     delete current;                     head = current;                     tail = current;                     cout << "\nobject found. list empty.\n";                 }                 else                 {                     cout << "\nobject not found.\n";                 }             }             else             {                 current = head;                  while(current->data != todelete && current->next != null)                 {                         trail = current;                         current = current->next;                 }                  if(current->data == todelete)                 {                     if(current->next == null)                     {                         trail->next = null;                         current = trail;                     }                     else                     {                         // having error here                         trail->next = current->next;                         current = trail;                         delete trail;                      }                      cout << "\nnode found , deleted.\n";                 }                 else                 {                     cout << "\nobject not found.\n";                 }             }         }          return head; } 

i marked specific line @ having trouble (when trying remove node middle (when next not null)). have tried multiple variations of block , still nothing.

all appreciated!

it looks assigning address current points to, same trail points to, , freeing resource, don't think intent.

right splitting list re-assign current point trail right before deleting trail (when wanted free current, based on while loop points want delete)

it makes more sense to:

trail->next = current->next; delete current;

i'm not sure how other cases working expected... code looks funny me. example, in case of being end of list you're not freeing resource (but deleted something, why no resource getting freed?) in case of deleting head, you've lost list , created memory leak current implementation.

all said - it's start, i'd take step , prototype interfaces linked-list should provide effective list out possible edge cases (such deleting head).


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -