c++ - Removing an element in the middle of a singly linked list? -


i'm implementing linked list , i'm having bit of trouble on function erases element. below function in entirety. if list empty, exit program. if list has single element, use function pop_back(); functional. lastly, if element in middle of list, iterate through list until find link right before it. assign pointer next link next link of node erased. function remove element, runs problem.

template <class t> void list<t>::erase(iterator & pos) {     node<t> * currentnode = pos.current;     node<t> * nextnode = pos.current->next;     node<t> * searchnode = head;      if (currentnode == 0) {         cout << "list empty. (erase)" << endl;         exit(0);     }     else if (nextnode == 0) {         pop_back();     }     else {         while (searchnode->next != currentnode) {             searchnode = searchnode->next;         }         searchnode->next = nextnode;         delete currentnode;         listsize--;     } } 

i used test code below make sure function works, seems break after removing element list.

int main() {     list<int> l;     l.push_front(5);     l.push_front(3);     l.push_back(31);     l.push_back(354);     l.push_front(63);     l.displaylist();     (listiterator<int>::iterator = l.begin(); != l.end(); it++) {         if (*it == 31) {             l.erase(it);             l.displaylist();         }     }     l.displaylist();     return 0; } 

here steps code goes through:

63 -> 3 -> 5 -> 31 -> 354 -> null (erase element 31) 63 -> 3 -> 5 -> 354 -> null 

through debugger able see after deleting 31, iterator positioned in null/illegal position in memory , terminates.

does have thoughts or suggestions?

here overloaded ++ operators:

template <class t> listiterator<t> & listiterator<t>::operator++() {     current = current->next;     return *this; }  template <class t> listiterator<t> & listiterator<t>::operator++(int) {     listiterator<t> savelist = listiterator(this);     current = current->next;     return savelist; } 

this loop no safe: after l.erase(it), iterator "it" no longer valid, loop keeps trying increment it.

for (listiterator<int>::iterator = l.begin(); != l.end(); it++) {     if (*it == 31) {         l.erase(it);         l.displaylist();     } } 

one way make safe break after erasing element:

for (listiterator<int>::iterator = l.begin(); != l.end(); it++) {     if (*it == 31) {         l.erase(it);         break;     } } 

Comments