CSE 116
Introduction To Computer Science for Majors 2
Lecture B
Lecture Notes
Stuart C. Shapiro
Spring, 2003
Stacks and Queues
Readings
Riley Chapter 7
Introduction
Stacks and queues are two classes of access-limited, mutable,
unbounded sequences. That they are "access-limited" means that
elements cannot be added or removed from them at any position.
Elements can be added to or removed from a stack at only one end (the
top). Elements can be added to a queue only at one end (the rear),
and removed only from the other end (the front).
Stacks
The Stack is one of the most important data structures in computer
science. Elements can be added to or removed from a stack at only one
end. Since we view this end as the "top" of the stack, we use the
term "push" for add, and the term "pop" for remove. Notice that the
element popped from a stack is always the last one pushed onto it
(among those still on it). Therefore, a stack is referred to as a
Last-In-First-Out (LIFO) list.
Examples of stacks in "real life":
The stack of trays in a cafeteria;
A stack of plates in a cupboard;
A driveway that is only one car wide. [Riley, p. 290]
Examples of stacks in computing:
Back/Forward stacks on browsers;
Undo/Redo stacks in Excel or Word;
Activation records of method calls;
The Stack ADT
Contains the methods push, pop,
empty, and peek (often called
top). See the java.util.Stack
API.
java.util.Stack
extends Vector, and so, is less restricted than the "official" stack,
but see the Go menu on a browser.
Queues
Elements can be added only at one end, the "rear", Elements can be
removed only at the other end, the "front". We call adding to a
queue "enqueueing", and removing from a queue "dequeueing". Since
the element dequeued is always the first one enqueued (among those
still on it), a queue is referred to as a First-In-First-Out (FIFO)
list.
Examples of queues in "real life":
A ticket line;
An escalator;
A car wash.
Examples of queues in computing:
A printer queue;
An input stream;
The Queue ADT
Contains the methods enqueue, dequeue,
front, isEmpty.
Two Implementations of Queues
LQueue and its API, a direct
implementation using a LinkdList and front and
rear pointers.