Deleting nodes of a value in a Linked List in C++ -


i'm practicing coding exercises website , can't figure out i'm doing wrong in implementation. can please let me know i'm going wrong in code?

the function removeelements should delete elements given value list. i'm trying obtain using function called removeelement (singular), , running until isn't able remove anything.

/** * definition singly-linked list. * struct listnode { *     int val; *     listnode *next; *     listnode(int x) : val(x), next(null) {} * }; */ class solution { public:     bool removeelement(listnode* head, int val) {         if (!head)             return false;          listnode* iterator = head;          //deal case head value deleted         if (head->val == val) {             head = head->next;             delete iterator;             if (head == null)                 delete head;             return true;         }          //head didn't match iterate through list         while (iterator->next) {              if (iterator->val == val) {                 listnode* temp = iterator->next;                 delete iterator;                 iterator = temp;                 return true;             }              iterator = iterator->next;          }//end while loop          //case tail value         if (iterator->val == val) {             delete iterator;             return true;         }          //otherwise return false         return false;     }//end function removeelement      listnode* removeelements(listnode* head, int val) {          //keep calling removeelement until returns false.         while (removeelement(head, val)) {         }          return head;     } }; 

the way delete linkedlist this:

iter->prev->next = iter->next; iter->next->prev = iter->prev; delete iter; 

this requires doubly linked list though, meaning each element points previous element. if don't want (or not allowed to) add this, can this:

if(iter->next && iter->next->val == val ){    node* deleteme = iter->next;    iter->next = iter->next->next;    delete deleteme; } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -