Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return an pointer to an item in the linear list

i have funcion that search a key in the linear list, but i have error when i want return pointer on an element.

struct Item
{
    datatype key;
    Item* next;
   Item* prev;
};

int List::search(int x)
{
    Item* temp = head;
    if (head == NULL)
    {
        cout << "Empty List" << endl;
    }
    while (temp != NULL)
    {
        if (temp->key == x) 
        {
            break;
        }
        else
        {
            temp = temp->next;
        }
    }
    return *temp;\\here i have a error
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to return an pointer to an item in the linear list

It is evident that for starters you need to change the return type of the function from int to Item *.

Item * List::search( int x );

And within function you need to return indeed a pointer instead of the pointed item.

The function should not output any message. It is the user of the function that will decide to output any message or not dependent on whether a null pointer is returned or not.

The function should be overloaded for constant and non-constant list.

Here is shown how it can be defined

Item * List::search( int x )
{
    Item *target = head;

    while ( target != nullptr && target->key != x )
    {
        target = target->next;
    }

    return target;
}

and

const Item * List::search( int x ) const
{
    const Item *target = head;

    while ( target != nullptr && target->key != x )
    {
        target = target->next;
    }

    return target;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading