Linked List is an efficient data structure to store data. You can learn about the basics of Linked List data structure in this wonderful post. In this session, we will explore the search operation in a Linked List.

As we discussed previously, any data structure that stores data has three basic operations:

Insertion: To insert data into the data structure

Deletion: To delete data from the data structure

Search: To search for a data in the data structure

In this leason, we will explore the search operation in a Linked List in depth.

The structure of a node in a Linked List is as follows:

The structure of a node in a doubly Linked List is as follows:

How to search an element in a Linked List?

To search an element in a Linked List, we need to traverse the entire Linked List and compare each node with the data to be search and continue until a match is found. We need to begin the search process from the first node as random access is not possible in a Linked List.

Pseudocode to search an element iteratively:

1) Initialize a node pointer, current = head.
2) Do following while current is not NULL
a) current->key is equal to the key being searched return true.
b) current = current->next
3) Return false

Why is searching in a Linked List slower than Arrays?

Considering that Linear Search is used in a Linked List and an Array, searching is always slower in a Linked List due to locality of reference. This is due to the following facts:

How Linked Lists are stored in memory?

How memory is accessed by the operating system?

Linked Lists are stored randomly (scattered) in memory.

When a data from a particular memory location is required, the operating system fetches additional data from the memory locations that are adjacent to the original memory location. The key idea is that the next memory location to be fetched is likely to be fetched from a nearby location and this has the potential to reduce the memory fetch operations. This concept is known as locality of reference.

As Linked Lists are stored randomly, the next data to be fetched is in a far memory location and hence, locality of reference does not reduce the memory access operations.

As arrays are sequentially, locality of reference plays a great role in making search operations in array faster.

Is binary search possible in Linked List?

Yes, binary search is possible in a Linked List povided the data is sorted.

The problem is that random access is not possible in a Linked List. Hence, accessing the middle element in a Linked List takes liner time. Therefore, the binary search takes O(N) time complexity instead of O(log N) in case of an array.

As binary search has no performance advantage compared to linear search in case of a Linked List, linear search is preferred due to simple implementation and single traversal of the Linked List.