c - Deleting in a linked list having many occurences of a value -
i using piece of code delete specific value linked list when create linked list having many occurrences of value. , if try delete value goes in infinite loop.
but when create linked list distinct values works fine. should do?
my code,
struct link** delete(int value, struct link** head) { struct link* temp=*head; struct link* q; if(head==null) { printf("error"); } else{ while(temp->data!=value){ q=temp; temp=temp->next; } q->next=temp->next; temp->next=null; free(temp); return head; } }
your algorithm has numerous problems. including, not limited to...
- dereference
temp
without checking null. undefined behavior if you're @ end of list ,temp
falls null. - there no return value if initial list pointer null.
- dereferencing
head
before checking null.
and others, but...
use head pointer-to-pointer advantage walk list address-of-links. , done properly, there no need return node pointer. head of list update as-needed if victim value happens occupy first node in list. following code remove all elements in list match specific value. can made considerably more efficient if list known-sorted, now:
void delete(int value, struct link** head) { if (!head) { printf("error"); return; } while (*head) { if ((*head)->data == value) { struct link *tmp = *head; *head = tmp->next; free(tmp); } else { head = &(*head)->next; } } }
that's it. important part of above code not advance pointer-to-pointer head
next link in chain if value being removed. instead, joins next value current node (the 1 deleted) resides. once done, target node "orphaned" , can safely delete it. *head
automatically references next node test.
edit: update single-item-removal-only (saw in general-comment)
void delete_one(int value, struct link** head) { if (!head) { printf("error"); return; } while (*head && (*head)->data != value) head = &(*head)->next; if (*head) { struct link *tmp = *head; *head = tmp->next; free(tmp); } }
best of luck
Comments
Post a Comment