c - Segmentation fault deleting nodes from singly linked list -
this case working on
[11] -> [12] -> [13] -> null i trying delete elements liked list above(example) maintain getting segfault , on running gdb doesnot help much. not looking reply , explanation on going wrong logically.
here code
int list:: remove( int val ) { listnode *headnode = _head; listnode *tempnode = null; if(headnode->_value == val){ tempnode = headnode->_next; delete headnode; _head = tempnode; } else { while(headnode->_value != val){ tempnode = headnode; headnode = headnode->_next; } tempnode->_next = headnode->_next; delete headnode; } }
you're not accounting next conditions:
the list may empty; i.e._head null; the value may not in list @ all. your function declared homecoming int, makes no such return assuming rest of code right (and big assumption), i'm all-but-certain you're trying do:
void list::remove( int val ) { listnode *headnode = _head; listnode *tempnode = null; while (headnode && headnode->_value != val) { tempnode = headnode; headnode = headnode->next; } if (headnode) { if (tempnode) tempnode->next = headnode->next; else _head = headnode->next; delete headnode; } } alternatively, if inclined can (arguably) simpler utilizing pointer-to-pointer traverse pointers in list, not values. worth investigating how next works, still covers bases described previously, using actual pointers in list nodes themselves, including _head, by-address rather by-value, thereby eliminating need walk-behind temporary pointer:
void list::remove( int val ) { listnode **pp = &_head; while (*pp && (*pp)->_value != val) pp = &(*pp)->next; if (*pp) { listnode *p = *pp; *pp = p->next; delete p; } } c
No comments:
Post a Comment