algoritmauzmanı
TREN
3.1Singly Linked List
Lesson 3.1.10

Searching for a value

Finding out whether a value is in the list, and at which position, is the first step of many operations such as deleting or updating. In a linked list the only way to do it is to start at the front and look at the nodes one by one. This method is called linear search.

What you will learn
  • How to count the position while walking the list, and how to return when the value is found
  • Why -1 is returned when the value is not in the list
  • Why searching is and why binary search does not help on a linked list
4 minTime O(n)Memory O(1)C · Java · Python
Know these first:3.1.3 Traversal

1Idea

Searching is a small change to traversal. temp starts at and at every compares the value with the one we are looking for. If they are equal it returns the current position; if not, it moves to the next node and adds one to the position. Positions start at 0.

When temp becomes we have reached the end of the list without finding the value. A valid position is never negative, so "not found" is reported as -1. In Python you could return None instead, but -1 is used here so that all three languages behave the same.

The function returns the first position where the value appears; if the value occurs more than once, the later ones are not checked. Sometimes the node itself is returned instead of its position, so the caller can change its value directly.

Even if the list is sorted, binary search does not help. Binary search relies on reaching the middle element in one step. In a linked list, reaching the middle node means walking half the list, so nothing is gained.

2Step by step

The drawing searches for 3 in a list holding 12, 7, 3 and 9. The last step shows what happens when the value is not in the list. At each step the matching line of code lights up.

NULL12?pos 07?pos 13?pos 29?pos 3headtemp
  1. Start. We are looking for 3. The position of each node is written under it.
  2. temp starts at the first node and pos at 0.
  3. 12 ≠ 3. temp moves to the next node and pos becomes 1.
  4. 7 ≠ 3. temp moves to the next node and pos becomes 2.
  5. 3 = 3. Found; the function returns 2. 9 was never looked at.
  6. If we were looking for 8, all four nodes would be compared. When temp becomes the loop ends and the function returns -1.

struct Node {    int data;    struct Node* next;}; int search(struct Node* head, int value) {    struct Node* temp = head;    int pos = 0;    while (temp != NULL) {        if (temp->data == value) return pos;        temp = temp->next;        pos++;    }    return -1;  // not found}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} int search(Node head, int value) {    Node temp = head;    int pos = 0;    while (temp != null) {        if (temp.data == value) return pos;        temp = temp.next;        pos++;    }    return -1;  // not found}
class Node:    def __init__(self, data):        self.data = data        self.next = None def search(head, value):    temp = head    pos = 0    while temp is not None:        if temp.data == value:            return pos        temp = temp.next        pos += 1    return -1  # not found

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

In the worst case (the value is last or missing) all n nodes are checked. If the value is in the first node, one comparison is enough.

Memory
O(1)

One pointer and one counter are used.

Faster searching needs a different structure. For example, in a balanced binary search tree a search takes .

4Common mistake

The most common mistake is putting only the value in the loop condition:

while (temp->data != value)  // if the value is missing, it reads from NULL    temp = temp->next;

If the value is in the list, this loop works. If it is not, temp ends up and temp->data is read until the program crashes. The condition must check temp != NULL first and compare the value only after that.

5Try it

What does search(head, 5) return for the list 5 → 8 → 5?

Show the answer

The answer is A. The function returns at the first match. The first node holds 5, so it returns 0 and never looks at the rest of the list.

Why does binary search not speed things up on a sorted linked list?

Show the answer

The answer is B. In an array the middle element is reached in one step by its . In a linked list every node is reached only through the one before it, so even finding the middle takes .

Lessons you mark show up in the curriculum. This is kept on this device only.