C SC 205 Lecture 10: Singly-Linked Lists
major resources: Data Structures and the Java Collections Framework Second Edition,
William Collins, McGraw-Hill, 2005
Introduction to Programming and OO Design
using Java, Niño and Hosch, Wiley & Sons, 2002
[ previous
| schedule
| next ]
Monday October 22 (week 7)
Linked list concept
- Each list entry created independently
- Each list entry explicitly linked to the next (and possibly previous) entry
- Access is inherently sequential, not direct
- We've already considered time efficiency of major operations
- Space efficient in the sense that no space is wasted (compared to array-based list)
- Space inefficient in the sense that each entry requires at least one reference as overhead
- Generic singly-linked list structure diagrammed
SinglyLinkedList class specification
- Developed for textbook
- Not part of Java Collections Framework
- Extends AbstractCollection
- Implements Iterable, Collection, and List
SinglyLinkedList class implementation
- As the name implies, is implemented using singly-linked list
- due to its rich heritage of super abstract classes and interfaces, it is obliged to
define a large number of methods!
- Most methods are defined to simply throw UnsupportedOperationException
- Note use of inner class for Entry data structure. Each Entry object
has reference to a list element and a reference to the next list Entry.
- We studied the source code for a few methods
- public SinglyLinkedList()
- public int size()
- public boolean isEmpty()
- public boolean contains(Object) (note that null elements are allowed, use of == and equals())
- public boolean add(E)
- Studied the inner class to implement its iterator
Inner class SinglyLinkedListIterator
- Is there any difference between an inner class and a nested class?
- Why define this as an inner class?
- Iterators and the Factory Pattern (design patterns are a topic for CSC 225)
- The iterator concept
- It maintains a pointer that rests between entries
- Initially to the left of first entry
-
- next() will advance it beyond the next entry and returns it
- hasNext() will be false after it advances past the last entry
- Thus you have to call next() to access the first element
- One-way iteration from beginning to end
- This class implements Iterator
- Obliged to define the boolean hasNext(), E next() and void remove() methods
- Also defines a constructor, but allows remove() to throw UnSupportedOperationException
[ C
SC 205 | Peter
Sanderson | Math Sciences server
| Math Sciences home page
| Otterbein ]
Last updated:
Peter Sanderson (PSanderson@otterbein.edu)