Lecture 6: More on Lists

Textbook reading: DJW Chap. 7, except 7.1.

Doubly Linked List

Doubly linked list; no header nodes; pointer to the end; no length field; separate List and Node classes; list may share tails.



Java library list classes

Sample usage: LL1.java

Iterator is an interface with methods hasNext() and next().
hasNext() is a boolean which is true if the collection has more elements to iterate over.
next() returns the next item and advances the iterator.
Note that next() always advances the iterator; if you need an element in the collection more than once, you have to save it in a variable.

Three ways to use an iterator

Iterators and the "for each" construction are defined in any class that implements the Iterable interface.

Ordered Lists

An ordered list is one in which the terms appear in increasing (or decreasing) order. For simplicity, we will consider ordered lists with no duplicates.

Ordered array list


Methods add and delete take only one argument, because there is no choice about where to put a new element.

Binary Search

Method Search(X) implements binary search:

Time requirement: Suppose there are 2K elements in the list. In the first iteration, you divide the list in half, so you are now looking at 2K-1 elements. In the second iteration, you divide this in half, so you are looking at 2K-2 elements. If you continue, you will reach a single element in K steps. Since the number of elements in the list N = 2K we have K=log2 N. So the time requirement for a binary search through N elements is proportional to log2N.

Useful powers of 2
24 = 16. So log216 = 4.
28 = 256. So log2256 = 8.
210 = 1024. So log21000 ≈ 10 .
216 = 65,336. So log265,336 = 16.
220 ≈ 1,000,000. So log21,000,000 ≈ 20.
230 ≈ 1,000,000,000. So log21,000,000,000 ≈ 30.
232 ≈ 4,000,000,000. So log24,000,000,000 ≈ 32.

Ordered Lists


No setters for the data fields.

Generic Ordered Lists



Comparable is a Java library interface. One method is compareTo(y). If x and y are objects in a class where compareTo is defined, then x.compareTo(y) returns: in whatever sense of "less", "equal", and "greater" make sense for this class.

Standard Java library classes in which "less" etc. make sense are defined as extensions of "Comparable" and have "compareTo" methods defined.

For a user-defined class, the programmer can feel free to define a "compareTo" method. But it has to satisfy the following properties:

A piece of code that uses compareTo generically should not make any other assumptions about its properties. However, if someone defines a compareTo method that does not satisfy these, then code that uses compareTo may behave very strangely.