SUNY Geneseo Department of Computer Science


Stacks

{Date}

CSci 141, Spring 2004
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture


Questions?

Density of primes

Careful about curve fitting

Stacks

Intro to chapter 12, section 12.2 through 12.2.4

Stack class in book is subclass of List

pop changes stack

Analogy to lists

[A Stack and a List]

Difference between stack and list

Another Implementation of Stacks

Argument: Stack shouldn't be a subclass of List at all, because stacks aren't quite lists (e.g., can't search a stack, concatenate stacks, remove an item without returning it, etc.)

But: It sure is convenient to build stack operations from List operations.

Design a Stack subclass that respects both of these arguments

Can "simulate" stack operations using a list

Hide this idea inside a Stack class

    class Stack {
        private List stackedData;
        public Stack() {
            stackedData = new List();
        }
        public void push( Object x ) {
            stackedData.addItem( x );
        }
        public Object pop() {
            return stackedData.getAndRemove();
        }
        public boolean isEmpty() {
            return stackedData.isEmpty();
        }
        public Object peek() {
            return stackedData.getFirst();
        }
    }

Example of "adaptor pattern"

But List and Stack are still similar in many ways. Maybe both should both be subclasses of some common "ur-list" class

[List and Stack as Subclasses of "UrList"]

Next

Introduction to Trees

Read sections 13.1, 13.2, 13.4


Next Lecture