The Department of Computer Science & Engineering
cse@buffalo
STUART C. SHAPIRO: CSE 116 B

CSE 116
Introduction To Computer Science for Majors 2
Lecture B
Lecture Notes
Stuart C. Shapiro
Spring, 2003


ArrayList (revisited) & Linked Lists

Reading
Riley, Chapter 5

ArrayList Revisited
ArrayLists are unbounded collections. Yet, an ArrayList uses an array, a bounded collection, internally to store the list. What does this mean for methods that add to an ArrayList, such as boolean add(Object o).

Also, since ArrayLists and arrays are sequential and indexed, how is a method such as Object remove(int index) implemented?

See BasicList.java, and its documentation for an example implementation of several ArrayList methods.

Linked Lists: Our first example of a Recursive Data Structure
Linked lists are unbounded, sequential collections that avoid the negatives of ArrayLists at the cost of not being random access. For a graphical example, see the simulator.

Java has a predefined version of LinkedList

We will look at two implementations.
The first, LinkList (documentation), has a straight-forward recursive structure, but is a bit dificult because the empty list is not a LinkList.
The second, LinkdList (documentation), is completely recursive---even the empty LinkdList is a LinkdList---by using a null Object.

For an application of linked lists, see SortedList.java and AddressBook.java.

Linked Lists vs. ArrayLists
Linked lists use 2 variables per element. ArrayLists use at most 2 variables per element. (If no/few removes.)
Linked lists require a linear scan to find the nth (or last) element. ArrayLists only need constant time.
Linked lists only need constant time to add one element, (given a pointer to the previous one). ArrayLists use "amortized constant time" [ArrayList API].
Linked lists can add an element at the front or in the middle in constant time. ArrayLists use linear time to shift all elements after it.
Linked lists can remove an element at the front or in the middle in constant time. ArrayLists use linear time to shift all elements after it.

First Previous Next

Copyright © 2003 by Stuart C. Shapiro. All rights reserved.

Stuart C. Shapiro <shapiro@cse.buffalo.edu>