Note: If you haven't covered the concept of linked lists, you can safely skip this section.
Sequential search is the most common search used on linked list structures. Let's take a look at how this search can be applied to linked lists.
We define our linked list structure as:
Our sequential search function for linked lists will take two arguments: a pointer to the first element in the list and the value for which we are searching. The function will return a pointer to the list structure containing the correct data, or will return NULL if the value wasn't found. Why do we need to pass in the number of elements in the array for the array version and not the number of elements in the list for the linked list version? Because we can easily tell when we're at the end of our list by checking to see if the element is NULL, whereas with our array the computer has no way of knowing how big it is without us telling it. Our function declaration is as follows:
Step 1: Just like the array version, we need to look at every element in the list, so we need a loop. We start at the first element in list, and while the current element is not NULL (meaning we haven't reached the end), we go on to the next element:
Step 2: If the current element contains the data we're looking for, then return a pointer to it.
Step 3: If after looking at every element in the list, we haven't found the value for which we are searching, then the value doesn't exist in the list. Return an error flag appropriately:
Step 4: Our final search function is:
We'll discuss why this search is used often for linked list after we look at non-linear searches.