CSC 102 Lecture Notes Week 8
More on Linked Lists and Iterators
Introduction to Recursion
More on Searching and Sorting
import java.util.*; /**** * * This class illustrates an iterative elementOf method. Compare it to the * recursive solution in ./RecursiveElementOf.java. */ public class IterativeElementOf { /** * Return true if the given element is in the given list, false if not. * The method uses a standard form of for loop to examine each element of * the list, returning true if we find the element we're looking for, false * if we run off the end of the list. */ static <E> boolean elementOf(List<E> list, E element) { for (int i = 0; i < list.size(); i++) { if (element.equals(list.get(i))) { return true; } } return false; } }
import java.util.*; /**** * * This class illustrates a recursive elementOf method. Compare it to the * iterative solution in ./IterativeElementOf.java. * */ public class RecursiveElementOf { /** * Return true if the given element is in the given list, false if not. * The method uses a recursive search algorithm, consisting of the * following three steps: * * (1) If the list is empty, return false. * * (2) If the element we're looking for is the first in the list, * return true. * * (3) Otherwise, search for the element recursively in the rest of the * list, i.e, the sublist from the second through the last element. */ <E> boolean elementOf(List<E> list, E element) { /* * Step 1. */ if (list.size() == 0) { return false; } /* * Step 2. */ if (list.get(0).equals(element)) { return true; } /* * Step 3. */ return elementOf(list.subList(1, list.size()), element); } }
. . . thinking . . .
Figure 1: Abstract data types for sequential and linked lists.