Linked list delete item

Hi,

I finally have some time, thanks to COVID-19, to go back and cement sections into my brain. This was an old project of mine where I had points taken off for my delete item not working.

Could someone walk me through what's wrong with this?

Thank you.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  void cdCollection::delete_item(string q){

    Node *deleteTemp, *clear;

    if(head == NULL){
        return;
    }

    else if(head -> name == q){
        clear = head;
        head = head -> next;
        delete clear;
    }

}
Last edited on
Your code will only work if the first item in the list matches string q. What if the matching item is in the middle of the list? What if it's at the end?
You need to traverse the linked list with some kind of loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void cdCollectgion::delete_by_name(std::string name) {
    if (head == nullptr)
        return;

    if (head->name == name) {
        Node* next = head->next;
        delete head;
        head = next;
        return;
    }

    for (Node* p{head->next}, prev{head}; p; prev = p, p = p->next) {
        if (p->name == value) {
            Node* next = p->next;
            delete p;
            prev->next = next;
            return;
        }
    }
}

... or something like that.
Last edited on
Oh, of course. It's obvious once pointed out.
Thanks fellas.
Topic archived. No new replies allowed.