mercredi 19 septembre 2018

Changing a function that guarantees a linear time worst case

struct Node
{
    T data;
    Node *next;
};
Node *front;
Node *back;

The below is a function that removes all the occurences of x in a linked list.

bool remove_first(const T &x)
{
    Node *p, *tmp;
    T dummy;

    if (front == nullptr)
        return false;
    if (front->data == x)
    {
        pop_front(dummy);
        return true;
    }
    p = front;
    while (p->next != nullptr)
    {
        if (x == p->next->data)
        {
            tmp = p->next;
            p->next = tmp->next;
            if (tmp == back)
                back = p;
            delete tmp;
            return true;
        }
        p = p->next;
    }
    return false;
}

Now, I have a function that searches for all the occurences of the element throughout the list and then deletes.

int slow(const T &x)
{
    int i = 0;
    while (remove_first(x))
        i++;
    return n;
}

Now how can I change this function such that it must guarantee linear time worst case runtime ("fast").

Can anyone please help me with this.

Aucun commentaire:

Enregistrer un commentaire