samedi 24 février 2018

Does it make a difference where I put this if statement?

So I was working on a lab with link lists and I got to a part where I have to output an error message if an element wasn't found after traversing the list. My question is, shouldn't it make a difference whether I put this if statement after the while loop or after the else statement? If I put it after the second else, shouldn't the function end as soon as that else finishes executing? I tried running it and I still got the same expected output, but I'm trying to figure out where it makes the most sense to put it since labs are graded on efficiency and style.

void AnyList::deleteNode(int deleteData)
{
    if (count == 0)
    {
        cerr << "Cannot delete from an empty list.\n";
    }
    else
    {
        Node *current = ptrToFirst; 
        bool found = false; 

        if (current->getData() == deleteData)
        {
            ptrToFirst = current->getPtrToNext();
            delete current;
            current = NULL;
            count--; 
            found = true; 
        }
        else
        {

            Node *trailCurrent = current;
            current = current->getPtrToNext(); 

            while (current != NULL && !found)
            {
                if (current->getData() == deleteData)
                {
                    trailCurrent->setPtrToNext(current->getPtrToNext());
                    delete current;
                    current = NULL;
                    trailCurrent = NULL;
                    count--;
                    found = true;
                }
                else
                {
                    trailCurrent = current; 
                    current = current->getPtrToNext();
                }
            }
            //if (!found)             <-- Does it make more sense to put it here?
            //{
            //  cerr << "Item to be deleted is not in the list.\n";
            //}

        }
        //if (!found)                 <-- Or here?
        //{
        //  cerr << "Item to be deleted is not in the list.\n";
        //}
    }

}

Aucun commentaire:

Enregistrer un commentaire