How to delete two items in a row in a linked list

前端 未结 2 1722
孤独总比滥情好
孤独总比滥情好 2021-01-24 09:41
void delete_double (LN*& l) {
    if (l == nullptr)
        return;

    LN *p = l;
    while ( p -> next != nullptr && p -> next -&g         


        
2条回答
  •  野性不改
    2021-01-24 10:30

    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;
    }
    

提交回复
热议问题