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