As you know, searching means looking for a value within the list and returning its index. We’ve seen that linear search on an array has a speed of O(N), since the computer needs to inspect each value one at a time.

Linked lists also have a search speed of O(N). To search for a value, we need go through a similar process as we did with reading. That is, we begin with the first node and follow the links of each node to the next one. Along the way, we inspect each value until we find what we’re looking for.

Code Implementation: Linked List Search

Here’s how we can implement the search operation in Ruby. We’ll call this method index_of , and pass in the value we’re searching for:

​  ​ def ​ ​ index_of ​(value)
​  ​ # We begin at the first node of the list: ​
​  current_node = first_node
​  current_index = 0
​  
​  ​ begin ​
​  ​ # If we find the data we're looking for, we return it: ​
​  ​ if ​ current_node.​ data ​ == value
​  ​ return ​ current_index
​  ​ end ​
​  
​  ​ # Otherwise, we move on the next node: ​
​  current_node = current_node.​ next_node ​
​  current_index += 1
​  ​ end ​ ​ while ​ current_node
​  
​  
​  ​ # If we get through the entire list without finding the ​
​  ​ # data, we return nil: ​
​  ​ return ​ ​ nil ​
​  ​ end ​

We can then search for any value within the list using:

​  list.​ index_of ​(​ "time" ​)

As you can see, the mechanics of searching are similar to reading. The main difference is that the loop doesn’t stop at a particular index, but runs until we either find the value or reach the end of the list.