c++ - Searching a Linked List -
below have linked list search function. function not searches element in list, set previous node's address, later used in delete function. if value found in list, node's address returned, otherwise previous node null , function returns null. receiving segmentation fault , unsure why. can explain me why? thanks.
struct intnodetype { int value; intnodetype * next; intnodetype (int v=0, intnodetype * p=null):value(v),next(p) { } }; intnodetype * search (intnodetype * firstnodeptr, int value, intnodetype * & prevnode) { intnodetype * cur; intnodetype * prev; cur = firstnodeptr; prev = prevnode; while (cur!=null) { if (cur->value==value) { prev -> next = cur; return cur; } cur = cur->next; //update p current node's next field } prevnode = null; return null; }
there 3 cases function:
the value trying find in first node , can tested using simple if statement
if(curr->value==value){return curr;}. case not required here guess because has no previous node pointing it, unless stated otherwise in question.the value in middle of list. in case should declare 2 pointers did, however, prev pointer should point first node , curr should point pre->next
curr=pre->next. in loop if value foundreturn curr;else move each pointer next nodepre=pre->next,curr=curr->next.the value not found , correctly executed in code.
now code. should have made sure pre node not set null because cause error when trying set next node. moreover, both pre , curr should traversed simultaneously don't lose connection between nodes when setting pre->next.
Comments
Post a Comment