Home > front end >  How to return an pointer to an item in the linear list
How to return an pointer to an item in the linear list

Time:11-06

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
}

CodePudding user response:

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

CodePudding user response:

Here:

int List::search(int x)
{
  Item* temp = head;
  ...
  return *temp;\\here i have a error
}

If you want to obtain a pointer to an element, then the function should return Item*, not int.

If temp is an Item*, then *temp is an Item. It is neither an Item* nor an int.

  • Related