I wrote a linked list and I don't understand how to realize a search element in the linked list.
I understand the first part of the code, but not the part that starts with if(found == true)
.
Thank you in advance if anyone decides to respond.
struct test_struct
{
int val;
struct test_struct *next;
};
struct test_struct *head = NULL;
struct test_struct *curr = NULL;
struct test_struct* create_list(int val)
{
...
}
struct test_struct *add_to_list(int val, bool add_to_end)
{
...
}
struct test_struct* search_in_list(int val, struct test_struct **prev)
{
struct test_struct *ptr = head;
struct test_struct *tmp = NULL;
bool found = false;
while (ptr != NULL)
{
if (ptr->val == val)
{
found = true;
break;
}
else
{
tmp = ptr; // here tmp play role of previous pointer
ptr = ptr->next;
}
}
if (true == found)
{
if (prev)
*prev = tmp;
return ptr;
}
else
{
return NULL;
}
}