Step 5 of 6
83% CompleteSearching Operations
Learn how to search for elements in a linked list
Searching in a Linked List
Searching is a fundamental operation in linked lists. There are two common search operations:
- Search by value: Find a node with a specific value
- Search by position: Find a node at a specific position
Let's explore both of these operations.
1. Search by Value
Searching for a node with a specific value requires traversing the list:
- Start at the head of the list
- Traverse the list, comparing each node's value with the target value
- Return the position if found, or -1 if not found
search(value) {// Start at the head of the listlet current = this.head;let position = 0;// Traverse the listwhile (current) {// If the current node's value matches the target, return the positionif (current.value === value) {return position;}// Move to the next nodecurrent = current.next;position++;}// If the value is not found, return -1return -1;}
The linked list is empty
Time Complexity: O(n) - In the worst case, we need to traverse the entire list to find the target value or determine it's not present.
2. Search by Position
Searching for a node at a specific position also requires traversing the list:
- Start at the head of the list
- Traverse the list until reaching the desired position
- Return the node's value if found, or null if the position is invalid
getAt(position) {// Start at the head of the listlet current = this.head;let count = 0;// Traverse the list until reaching the desired positionwhile (current) {if (count === position) {return current.value;}// Move to the next nodecurrent = current.next;count++;}// If the position is invalid, return nullreturn null;}
The linked list is empty
Time Complexity: O(n) - In the worst case, we need to traverse to the end of the list, making this a linear-time operation.
Optimizing Search Operations
Linked lists are not optimized for search operations. Here are some considerations:
- No random access: Unlike arrays, linked lists don't support direct indexing, so we always need to traverse from the head.
- No binary search: Since we can't jump to the middle of a linked list in constant time, we can't use binary search algorithms.
- Alternative data structures: If your application requires frequent searches, consider using arrays, hash tables, or binary search trees instead.
Performance Comparison
Interactive Example
Try searching for values in the linked list below:
The linked list is empty
Use the controls to add nodes
Check Your Understanding
Next Steps
Now that you understand how to search for elements in a linked list, let's move on to learning about traversal operations in the next tutorial.