SUNY Geneseo Department of Computer Science


List Algorithms and List Subclasses

{Date}

CSci 141, Spring 2005
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture


Questions?

printList vs printListForward

[Printing a List in Forward and Reverse Order]

List Algorithms

Given a list of numbers, return the first odd one (or 0 if the list contains no odd numbers)

    // In class List...
    // Precondition: list contains only integers
    int firstOdd()
        if ! this.isEmpty()
            if this.getFirst() % 2 != 0
                return this.getFirst()
            else
                return this.getRest().firstOdd()
        else
            return 0

How fast is it (in terms of n items in list)?

Theta notation?

[3n+1 Rises Proportionally to n]

Subclasses of List

Read Section 11.5 through subsection 11.5.2

Constructing additional methods requires extending class

Two problems

Casting assures compiler that items have types programmer knows they do

Nomenclature

    private Object head;
    public List() {
        head = null;
    ...
    public Object getFirst() {
        return this.head;
    }

Break constructor into 2 parts

Idea is that method that creates new list uses helper rather than constructor

    addItem( x )
        temp = new List()
        temp.head = this.head
        temp.rest = this.rest
        this.rest = temp
        this.head = x

[Adding an Item to A List Works]

[Adding Item to Subclass Leaves Tail with Wrong Type]


Next Lecture