void delete_double (LN*& l) {
if (l == nullptr)
return;
LN *p = l;
while ( p -> next != nullptr && p -> next -&g
Before or after you delete p, the item before p should point to the item after the two deleted items. Otherwise, the link list will broken.
Furthermore, for the while-loop, you may only stop when you arrive the last item. Otherwise, if the last two items are the same, you cannot correctly delete it.
Here is my version. I used a dummy item to point to the item before the current compared item. Notice this cannot deal with 3 items in a row.
void delete_double (LN*& l) {
if (l == nullptr)
return;
LN *dummy = new LN;
dummy -> next = l;
while ( dummy -> next != nullptr && dummy -> next -> next != nullptr) // search until the last but two item
{
if (dummy -> next -> value == dummy -> next -> next -> value) // the current value is equal to the next value in the linked list
{
dummy -> next = dummy -> next -> next -> next; // link the item after dummy to the item after the deleted items
}
dummy = dummy -> next; // move dummy to the next, notice that this cannot deal with 3 items in a row
}
return;
}