next up previous
Next: Inserting a new element Up: Unit 11 Previous: Printing the elements of

Searching an element in a list

To check whether an element in present in a list, we can ``scan'' the list until: -

Iterative implementation:

public static boolean search(ListNode lis, String s) {
  while (lis != null) {
    if (lis.info.equals(s)) return true;
    lis = lis.next;
  }
  return false;
}

We can also characterize recursively the operation of checking whether an element elem is present in a list lis as follows:

  1. if lis is empty, then return false (base case);
  2. otherwise, if elem is the first element of lis, then return true (base case);
  3. otherwise, return the result of searching elem in the rest of lis (recursive case).

Given such a characterization, the recursive implementation is immediate. We leave it as an exercise.


next up previous
Next: Inserting a new element Up: Unit 11 Previous: Printing the elements of