I'm new to C++ and I'm trying to write an algorithm to search a linked list, but I'm having a little trouble with my logic. The ??? question marks in bold are the parts I'm having trouble with. I appreciate any help with this.
ListNode *MyLinkedList::Search(int key)
{
ListNode *temp = head; // Assume ListNode is a structure and contains the variable int key;
// Search for the key
while((temp != NULL) && (key != temp->key))
{
temp = temp -> next; // Advance to next node
{
if(**???**) // Make sure node is found
{
return **???**; // If found, return appropriate value
}
else
{
return NULL; // return NULL when not found
}
}
If the key was found key == temp->key
will be true and temp != NULL
will be false, so:
if(key == temp->key) // Make sure node is found
{
return temp; // If found, return appropriate value
}
OR:
if (temp != NULL) // Make sure node is found
{
return temp; // If found, return appropriate value
}
Try this code:
ListNode *MyLinkedList::Search(int key, ListNode *head)
{
ListNode *temp = head; // Assume ListNode is a structure and contains the variable int key;
// Search for the key
while(temp != NULL)
{
if (key == temp->key)
return temp;
temp = temp -> next; // Advance to next node
}
return NULL; // return NULL when not found
}
EDIT
You should use the list from stl and the find algorithm, if you aren't required to write your own container; They are tested and safe:
You don't need an if
. Just return temp
. If the correct key is present in the list, temp
would be pointing to it, otherwise it's NULL
.
This will work for you
if(temp != NULL) // Make sure node is found
{
return temp; // Make sure node is found
}
You could do this:
if(temp != NULL) // Make sure node is found
{
return temp; // If found, return appropriate value
}
But much simpler is just
return temp;
since if temp is null, you want to return null anyway.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.