0% found this document useful (0 votes)
70 views

Stacks, Queues, and Deques: Data Structures and Algorithms With Object-Oriented Design Patterns in Python

learn stacks

Uploaded by

Vishal Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views

Stacks, Queues, and Deques: Data Structures and Algorithms With Object-Oriented Design Patterns in Python

learn stacks

Uploaded by

Vishal Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Stacks, Queues, and Deques Page 1 of 2

Data Structures and Algorithms with Object-Oriented Design Patterns in Python

Stacks, Queues, and Deques

In this chapter we consider several related abstract data types--stacks, queues, and deques. Each of
these can be viewed as a pile of items. What distinguishes each of them is the way in which items are
added to or removed from the pile.

In the case of a stack, items are added to and removed from the top of the pile. Consider the pile of
papers on your desk. Suppose you add papers only to the top of the pile or remove them only from
the top of the pile. At any point in time, the only paper that is visible is the one on top. What you
have is a stack.

Now suppose your boss comes along and asks you to complete a form immediately. You stop doing
whatever it is you are doing, and place the form on top of your pile of papers. When you have filled-
out the form, you remove it from the top of the stack and return to the task you were working on
before your boss interrupted you. This example illustrates that a stack can be used to keep track of
partially completed tasks.

A queue is a pile in which items are added an one end and removed from the other. In this respect, a
queue is like the line of customers waiting to be served by a bank teller. As customers arrive, they
join the end of the queue while the teller serves the customer at the head of the queue. As a result, a
queue is used when a sequence of activities must be done on a first-come, first-served basis.

Finally, a deque extends the notion of a queue. In a deque, items can be added to or removed from
either end of the queue. In a sense, a deque is the more general abstraction of which the stack and the
queue are just special cases.

As shown in Figure , we view stacks, queues, and deques as containers. This chapter presents a

classes presented are extensions of the abstract Container class defined in Chapter .

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Stacks, Queues, and Deques Page 2 of 2

Figure: Object class hierarchy.

Stacks
Queues
Deques
Exercises
Projects

Copyright © 2003 by Bruno R. Preiss, P.Eng. All rights reserved.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Page 1 of 1

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/index.html 22/05/2018
Stacks Page 1 of 2

Data Structures and Algorithms with Object-Oriented Design Patterns in Python

Stacks
The simplest of all the containers is a stack . A stack is a container which provides exactly one
method, push, for putting objects into the container; and one method, pop, for taking objects out of
the container. Figure

Figure: Basic stack operations.

Objects which are stored in a stack are kept in a pile. The last item put into the stack is a the top.
When an item is pushed into a stack, it is placed at the top of the pile. When an item popped, it is
always the top item which is removed. Since it is always the last item to be put into the stack that is
the first item to be removed, a stack is a last-in, first-out or LIFO data structure.

In addition to the push and pop operations, the typical stack implementation also has a property
called top that returns the item at the top of the stack without removing it from the stack.

Program defines the Stack class. The abstract Stack class extends the abstract Container class
defined in Program -Program . Hence, it comprises all of the methods inherited from
Container plus the push and pop methods and the Top property.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Stacks Page 2 of 2

Program: Abstract Stack class.

When implementing a data structure, the first issue to be addressed is which foundational data
structure(s) to use. Often, the choice is between an array-based implementation and a linked-list
implementation. The next two sections present an array-based implementation of stacks followed by
a linked-list implementation.

Array Implementation
Linked-List Implementation
Applications

Copyright © 2003 by Bruno R. Preiss, P.Eng. All rights reserved.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Data Structures and Algorithms with Object-Oriented Design Patterns in Python Page 1 of 1

Data Structures and Algorithms with Object-Oriented Design Patterns in Python

Data Structures and Algorithms


with Object-Oriented Design Patterns in
Python
Bruno R. Preiss
B.A.Sc., M.A.Sc., Ph.D., P.Eng.

Colophon
Dedication
Preface
Introduction
Algorithm Analysis
Asymptotic Notation
Foundational Data Structures
Data Types and Abstraction
Stacks, Queues, and Deques
Ordered Lists and Sorted Lists
Hashing, Hash Tables, and Scatter Tables
Trees
Search Trees
Heaps and Priority Queues
Sets, Multisets, and Partitions
Garbage Collection and the Other Kind of Heap
Algorithmic Patterns and Problem Solvers
Sorting Algorithms and Sorters
Graphs and Graph Algorithms
Python and Object-Oriented Programming
Class Hierarchy Diagrams
Character Codes
References
Index

Copyright © 2003 by Bruno R. Preiss, P.Eng. All rights reserved.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/boo... 22/05/2018
Projects Page 1 of 1

Data Structures and Algorithms with Object-Oriented Design Patterns in Python

Projects
1. Design and implement suitable wrapper classes that extend the Object base class for the
Python types bool, int, str, and tuple.
2. Using visitors, devise an implementation for the __contains__ method and the find method
of the SearchableContainer class declared in Program .
3. Using an iterator, devise an implementation for the __contains__ method and the find
method of the SearchableContainer class declared in Program .
4. Devise a scheme using visitors whereby all of the objects contained in one searchable
container can be removed from it and transfered to another container.
5. A bag is a simple container that can hold a collection of objects. Design and implement a
concrete class called Bag that extends the SearchableContainer class defined in Program .
Use the Array class given in Chapter to keep track of the contents of the bag.
6. Repeat Project , this time using the LinkedList class given in Chapter .
7. In Java it is common to use an enumeration as the means to iterate through the objects in a
container. In Python we can define an enumeration like this:

class Enumeration(Object):
def hasMoreElements():
pass
hasMoreElements = abstractmethod(hasMoreElements)

def nextElement():
pass
nextElement = abstractmethod(nextElement)

Given an enumeration e from some container c, the contents of c can be printed like this:

while (e.hasMoreElements()):
print e.nextElement()

Devise a wrapper class to encapsulate a Python iterator and provide the functionality of a Java
enumeration.

Copyright © 2003 by Bruno R. Preiss, P.Eng. All rights reserved.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 1 of 23

Data Structures and Algorithms with Object-Oriented Design Patterns in Python

Index
o
seebig oh, seelittle oh

seeEuler's constant
seeomega
seetheta
seelambda
__init__ method
__init__ Method
abstract algorithms
Tree Traversals
abstract class
Class Hierarchy, Class Hierarchy, Class Hierarchy, Algorithmic Abstraction
abstract data type
Foundational Data Structures, Abstract Data Types
abstract method
Class Hierarchy
abstract property
Class Hierarchy
abstract solver
Abstract Backtracking Solvers
abstract sorter
Sorting and Sorters
access path
Inserting Items into an
accessor
Array Properties, Array Properties, PropertiesAccessors and Mutators
activation record
The Basic Axioms
activity-node graph
Application: Critical Path Analysis
actual parameter
Parameter Passing
acyclic
directed graph
Directed Acyclic Graphs
adapter
PreorderInorder, and Postorder , PreorderInorder, and Postorder
address
Abstract Data Types
adjacency lists
Adjacency Lists
adjacency matrix
Adjacency Matrices
adjacent

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 2 of 23

Terminology
ADT
seeabstract data type
algorithmic abstraction
Algorithmic Abstraction
ancestor
More Terminology
proper
More Terminology
and
UnionIntersection, and Difference
annealing
Simulated Annealing
annealing schedule
Simulated Annealing
arc
directed
Terminology
undirected
Undirected Graphs
arithmetic series
About Arithmetic Series Summation
arithmetic series summation
An example-Geometric Series Summation, About Arithmetic Series Summation
arity
N-ary Trees
array
Foundational Data Structures
ASCII
Character String Keys
association
Searchable Containers
asymptotic behavior
Asymptotic Notation
attribute
class
InstancesInstance Attributes and
instance
InstancesInstance Attributes and
attributes
Abstract Data Types
AVL balance condition
AVL Search Trees
AVL rotation
Balancing AVL Trees
AVL tree
Basics
B-Tree
B-Trees, B-Trees
Bachmann, P.
An Asymptotic Upper Bound-Big
backtracking algorithms
Backtracking Algorithms
bag
Projects, Multisets

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 3 of 23

balance condition
AVL Search Trees, B-Trees
AVL
AVL Search Trees
base class
Class Hierarchy, Derivation and Inheritance
big oh
An Asymptotic Upper Bound-Big
tightness
Tight Big Oh Bounds, More Notation-Theta and Little
tightness
Tight Big Oh Bounds, More Notation-Theta and Little
transitive property
Properties of Big Oh
binary digit
Binomial Queues
binary heap
Sorting with a Heap
binary operator
Applications
binary search
Locating Items in an , Example-Binary Search
binary search tree
Binary Search Trees, Binary Search Trees
binary tree
Binary Trees, Binary Trees
complete
Complete Trees
binding
Abstract Data Types, Names
binomial
Binomial Trees
binomial coefficient
Binomial Trees
bit
Binomial Queues
Boolean
and
UnionIntersection, and Difference
or
UnionIntersection, and Difference
bound
Abstract Data Types
branch-and-bound
Branch-and-Bound Solvers
breadth-first spanning tree
Constructing Spanning Trees
breadth-first traversal
Applications, Applications, Breadth-First Traversal, Example-Balancing Scales, Breadth-First
Traversal
brute-force algorithms
Brute-Force and Greedy Algorithms
bubble sort
Bubble Sort
bucket sort

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 4 of 23

Example-Bucket Sort
buckets
Example-Bucket Sort
built-in scope
Scopes and Namespaces
C++ programming language
Abstract Data Types
carry
Merging Binomial Queues
ceiling function
About Harmonic Numbers
central limit theorem
Exercises
chained scatter table
Chained Scatter Table
child
Applications, Terminology
circular list
Singly-Linked Lists, Doubly-Linked and Circular Lists
class
Classes
abstract
Algorithmic Abstraction
classic
Abstract Objects and the , Derivation and Inheritance
classic
Abstract Objects and the , Derivation and Inheritance
new-style
Abstract Objects and the , Derivation and Inheritance
new-style
Abstract Objects and the , Derivation and Inheritance
class attribute
InstancesInstance Attributes and
classic class
Abstract Objects and the , Derivation and Inheritance
clock frequency
A Simplified Model of
clock period
A Simplified Model of
coalesce
Chained Scatter Table
cocktail shaker sort
Exercises
coefficient
binomial
Binomial Trees
collapsing find
Collapsing Find
column-major order
Exercises
commensurate
elements
Sorted Lists, Basics
elements
Sorted Lists, Basics

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 5 of 23

functions
More Big Oh Fallacies , More Big Oh Fallacies
functions
More Big Oh Fallacies , More Big Oh Fallacies
compact
The Fragmentation Problem
compaction
Mark-and-Compact Garbage Collection
complement
Exercises
complete N-ary tree
Complete N-ary Trees
complete binary tree
Complete Trees, Sorting with a Heap
complex numbers
Example-Complex Numbers
component
connected
Connectedness of an Undirected
compound statement
Rules For Big Oh
concrete class
Class Hierarchy, Class Hierarchy
conjunction
SetsMultisets, and Partitions
connected
undirected graph
Connectedness of an Undirected
connected component
Connectedness of an Undirected , Exercises
conquer
seedivide
constant
Conventions for Writing Big
ContainerEmpty
first and last Properties
copy
__copy__ Method
shallow
__copy__ Method
counted do loop
Rules For Big Oh
critical activity
Application: Critical Path Analysis
critical path
Application: Critical Path Analysis
critical path analysis
Application: Critical Path Analysis
cubic
Conventions for Writing Big
cycle
More Terminology
negative cost
Single-Source Shortest Path
simple

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 6 of 23

More Terminology
dangling pointer
What is Garbage?
dangling reference
What is Garbage?
data ordering property
M-Way Search Trees
database
Associations
decision tree
A Lower Bound on
defragment
The Fragmentation Problem
degree
Applications
in
Terminology
out
Terminology
dense graph
Sparse vs. Dense Graphs
depth
More Terminology
depth-first spanning tree
Constructing Spanning Trees
depth-first traversal
Example-Balancing Scales, Depth-First Traversal
deque
StacksQueues, and Deques, Deques
derivation
Class Hierarchy, Derivation and Inheritance
derivative
Applications
derived class
Derivation and Inheritance
descendant
More Terminology
proper
More Terminology
descriptor
Abstract Methods
difference
SetsMultisets, and Partitions, Basics, UnionIntersection, and Difference
symmetric
Exercises
differentiation
Applications
digit
binary
Binomial Queues
digraph
seedirected graph
Dijkstra's algorithm
Dijkstra's Algorithm
directed acyclic graph

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 7 of 23

Directed Acyclic Graphs


directed arc
Terminology
directed graph
Directed Graphs
discrete event simulation
Discrete Event Simulation
disjunction
SetsMultisets, and Partitions
distribution sorting
Distribution Sorting
distribution sorts
Sorter Class Hierarchy
divide and conquer
Top-Down Algorithms: Divide-and-Conquer
division method of hashing
Division Method
double hashing
Double Hashing
double rotation
Double Rotations
double-ended queue
Deques
doubly-linked list
Doubly-Linked and Circular Lists
dual
Application: Critical Path Analysis
dynamic binding
Abstract Data Types
dynamic programming
Bottom-Up Algorithms: Dynamic
Programming
earliest event time
Application: Critical Path Analysis
edge
Applications, Terminology
emanate
Terminology
incident
Terminology
element
SetsMultisets, and Partitions
emanate
Terminology
enumeration
Projects
equivalence classes
Applications
equivalence of trees
Comparing Trees
equivalence relation
Applications, Kruskal's Algorithm
Euler's constant
About Harmonic Numbers, Solving The Recurrence-Telescoping, Average Running Time
Euler, Leonhard

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 8 of 23

Binomial Trees
Eulerian walk
Exercises
evaluation stack
Postfix Notation
event-node graph
Application: Critical Path Analysis
exception
first and last Properties, extract Method
exception handler
Exceptions
exceptions
Exceptions
exchange sorting
Exchange Sorting
exchange sorts
Sorter Class Hierarchy
exclusive or
Character String Keys, Character String Keys
exponent
Floating-Point Keys
exponential
Conventions for Writing Big
exponential cooling
Simulated Annealing
exponential distribution
Exponentially Distributed Random Variables
expression tree
Expression Trees
extend
Example-Graphical Objects
external node
N-ary Trees
external path length
Unsuccessful Search
factorial
Analyzing Recursive Methods
feasible solution
Brute-Force Algorithm
Fibonacci hashing method
Fibonacci Hashing
Fibonacci number
Fibonacci Hashing, AVL Search Trees
Fibonacci numbers
Example-Fibonacci Numbers, Example-Computing Fibonacci Numbers
closed-form expression
Example-Fibonacci Numbers
generalized
Example-Generalized Fibonacci Numbers
FIFO
Queues
fifo-in, first-out
Queues
find
collapsing

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 9 of 23

Collapsing Find
floor function
About Harmonic Numbers
Floyd's algorithm
Floyd's Algorithm
forest
Binomial Queues, Binomial Queues, Implementing a Partition using
formal parameter
Parameter Passing
foundational data structure
Foundational Data Structures
fully connected graph
Exercises
garbage
What is Garbage?
garbage collection
What is Garbage?
mark-and-compact
Mark-and-Compact Garbage Collection
mark-and-sweep
Mark-and-Sweep Garbage Collection
reference counting
Reference Counting Garbage Collection
stop-and-copy
Stop-and-Copy Garbage Collection
Gauss, Karl Friedrich
Binomial Trees
generalized Fibonacci numbers
Example-Generalized Fibonacci Numbers
geometric series
About Geometric Series Summation
geometric series summation
An example-Geometric Series Summation, Example-Geometric Series Summation Again,
About Geometric Series Summation, Example-Geometric Series Summation Yet
getter
PropertiesAccessors and Mutators
global scope
Scopes and Namespaces
golden ratio
Fibonacci Hashing
graph
connectedness
Connectedness of an Undirected
dense
Sparse vs. Dense Graphs
directed
Directed Graphs
directed acyclic
Directed Acyclic Graphs
labeled
Labeled Graphs
sparse
Sparse vs. Dense Graphs
traversal
Graph Traversals

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 10 of 23

undirected
Undirected Graphs
graph theory
Graphs and Graph Algorithms
handle
Handles
harmonic number
Average Running Times, About Harmonic Numbers, Average Case Analysis, Solving The
Recurrence-Telescoping, Average Running Time
harmonic series
About Harmonic Numbers
hash function
Keys and Hash Functions, Keys and Hash Functions
hash table
Hash Tables
hashing
division method
Division Method
Fibonacci method
Fibonacci Hashing
middle-square method
Middle Square Method
multiplication method
Multiplication Method
head
Singly-Linked Lists
heap
Basics, Garbage Collection and the
heapify
Sorting with a Heap
heapsort
Sorting with a Heap
height
of a node in a tree
More Terminology
of a tree
More Terminology
heuristic
Depth-FirstBranch-and-Bound Solver
hierarchy
Trees
Horner's rule
Another example-Horner's Rule, Example-Geometric Series Summation Again, Character
String Keys
in-degree
Terminology, Topological Sort
in-place sorting
Insertion Sorting, Selection Sorting
incident
Terminology
increment
Generating Random Numbers
infix
Applications
infix notation

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 11 of 23

Infix Notation
inheritance
Derivation and Inheritance
multiple
Derivation and Inheritance
inorder traversal
Inorder Traversal, Traversing a Search Tree
M-way tree
Traversing a Search Tree
insertion sorting
Insertion Sorting
straight
Straight Insertion Sort
insertion sorts
Sorter Class Hierarchy
instance
InstancesInstance Attributes and
instance attribute
InstancesInstance Attributes and
internal node
N-ary Trees
internal path length
Unsuccessful Search
complete binary tree
Complete Trees
internal path length of a tree
Successful Search
Internet domain name
Character String Keys
intersection
SetsMultisets, and Partitions, Basics, UnionIntersection, and Difference
interval
search
Locating Items in an
inverse modulo W
Multiplication Method
inversion
Average Running Time
isomorphic
Alternate Representations for Trees
isomorphic trees
Exercises
iterative algorithm
Example-Fibonacci Numbers
iterator
Iterators
iterator protocol
Iterators
Java programming language
Abstract Data Types
key
Associations, Keys and Hash Functions
keyed data
Using Associations
KeyError

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 12 of 23

extract Method
knapsack problem
Example-0/1 Knapsack Problem
Kruskal's algorithm
Kruskal's Algorithm
L'Hôpital's rule
About Logarithms, About Logarithms
labeled graph
Labeled Graphs
lambda
seeload factor
last-in, first-out
Stacks
latest event time
Application: Critical Path Analysis
leaf
Terminology
leaf node
N-ary Trees
least-significant-digit-first radix sorting
Radix Sort
left subtree
Binary Trees, M-Way Search Trees
leftist tree
Leftist Trees
level
More Terminology
level-order
Complete N-ary Trees
level-order traversal
Applications
lexicographic order
Array Subscript Calculations
lexicographic ordering
Radix Sort
lexicographically precede
Radix Sort
LGB rule
Scopes and Namespaces
lifetime
Abstract Data Types, Abstract Data Types, Objects and Types
LIFO
Stacks
limit
Properties of Big Oh
linear
Conventions for Writing Big
linear congruential random number generator
Generating Random Numbers
linear probing
Linear Probing
linear search
Yet Another example-Finding the
linked list
Foundational Data Structures

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 13 of 23

list
Ordered Lists and Sorted
little oh
More Notation-Theta and Little
live
Mark-and-Sweep Garbage Collection
LL rotation
Single Rotations
in a B-tree
Removing Items from a
load factor
Average Case Analysis
local scope
Scopes and Namespaces
log squared
Conventions for Writing Big
logarithm
Conventions for Writing Big
long integer
The Basic Axioms
loop
More Terminology
loose asymptotic bound
More Notation-Theta and Little
LR rotation
Double Rotations
ukasiewicz, Jan
Applications
M-way search tree
M-Way Search Trees
mantissa
Floating-Point Keys
many-to-one mapping
Keys and Hash Functions
mark-and-compact garbage collection
Mark-and-Compact Garbage Collection
mark-and-sweep garbage collection
Mark-and-Sweep Garbage Collection
matrix
Matrices
adjacency
Adjacency Matrices
sparse
Adjacency Matrices
max-heap
Sorting with a Heap
median
Selecting the Pivot
median-of-three pivot selection
Selecting the Pivot
memory leak
What is Garbage?
merge sort
Example-Merge Sorting
merge sorting

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 14 of 23

Merge Sorting
merge sorts
Sorter Class Hierarchy
mergeable priority queue
Basics
merging nodes in a B-tree
Removing Items from a
Mersenne primes
The Minimal Standard Random
method
static
Static Methods
method resolution order
Multiple Inheritance
middle-square hashing method
Middle Square Method
min heap
Basics
minimal subgraph
Minimum-Cost Spanning Trees
minimum spanning tree
Minimum-Cost Spanning Trees
mixed linear congruential random number generator
Generating Random Numbers
modulus
Generating Random Numbers
Monte Carlo methods
Monte Carlo Methods
multi-dimensional array
Multi-Dimensional Arrays
multiple inheritance
Derivation and Inheritance
multiplication hashing method
Multiplication Method
multiplicative linear congruential random number generator
Generating Random Numbers
multiset
Multisets
mutator
PropertiesAccessors and Mutators
N-ary tree
N-ary tree
N-ary Trees
N-queens problem
N-queens problem
Exercises
name
Abstract Data Types, Abstract Data Types, Abstract Data Types, Names
namespace
Scopes and Namespaces
Nary tree
textbf
negative cost cycle
Single-Source Shortest Path
nested class

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 15 of 23

Implementation, Nested Classes


new-style class
Abstract Objects and the , Derivation and Inheritance
Newton, Isaac.
Binomial Trees
node
Applications, Basics, N-ary Trees, Binary Trees, Terminology
non-recursive algorithm
Example-Fibonacci Numbers
normalize
Generating Random Numbers
null path length
Leftist Trees, Leftist Trees
object
Objects and Types
object-oriented programming
Abstract Data Types
object-oriented programming language
Abstract Data Types
objective function
Brute-Force Algorithm
odd-even transposition sort
Exercises
omega
An Asymptotic Lower Bound-Omega
open addressing
Scatter Table using Open
operator overloading
Operator Overloading
operator precedence
Applications
optimal binary search tree
Exercises
or
UnionIntersection, and Difference
ordered list
Ordered Lists and Sorted
ordered tree
N-ary Trees, Binary Trees
ordinal number
Positions of Items in
oriented tree
N-ary Trees
out-degree
Terminology
overloading operators
Operator Overloading
override
Class Hierarchy, Derivation and Inheritance, Derivation and Inheritance
parameter passing
Parameter Passing
parent
Applications, Terminology
parentheses
Applications

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 16 of 23

partial order
Comparing Sets
partition
Partitions, Kruskal's Algorithm
Pascal's triangle
Example-Computing Binomial Coefficients
Pascal, Blaise
Example-Computing Binomial Coefficients
pass-by-reference
Parameter Passing
path
Terminology
access
Inserting Items into an
path length
external
Unsuccessful Search
internal
Unsuccessful Search
weighted
Shortest-Path Algorithms
perfect binary tree
Searching a Binary Tree, AVL Search Trees
period
Generating Random Numbers
pivot
Quicksort
plain integer
The Basic Axioms
Polish notation
Applications
polymorphism
Class Hierarchy, Polymorphism
polynomial
About Polynomials, About Polynomials Again
postcondition
Inserting Items in a
postorder traversal
Postorder Traversal
power set
Array and Bit-Vector Sets
precede lexicographically
Radix Sort
precondition
Inserting Items in a
predecessor
Instance Attributes, More Terminology
prefix notation
Prefix Notation
preorder traversal
Preorder Traversal
prepend
prepend Method
Prim's algorithm
Prim's Algorithm

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 17 of 23

primary clustering
Linear Probing
prime
relatively
Multiplication Method
priority queue
mergeable
Basics
probability density function
Exponentially Distributed Random Variables
probe sequence
Scatter Table using Open
proper subset
Comparing Sets
proper superset
Comparing Sets
pruning a solution space
Branch-and-Bound Solvers
pseudorandom
Generating Random Numbers
Python programming language
Abstract Data Types
quadratic
Conventions for Writing Big
quadratic probing
Quadratic Probing
queue
StacksQueues, and Deques
quicksort
Quicksort
radix sorting
Radix Sort
raise
Exceptions
random number generator
linear congruential
Generating Random Numbers
mixed linear congruential
Generating Random Numbers
multiplicative linear congruential
Generating Random Numbers
random numbers
Generating Random Numbers
random variable
Random Variables
rank
Union by Height or
record
Abstract Data Types
recurrence relation
Analyzing Recursive Methods
recursive algorithm
Analyzing Recursive Methods, Example-Fibonacci Numbers
reference count
Reference Counting Garbage Collection

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 18 of 23

reference counting garbage collection


Reference Counting Garbage Collection
reflexive
Applications
relation
equivalence
Applications
relatively prime
Multiplication Method
repeated substitution
Solving Recurrence Relations-Repeated Substitution
Reverse-Polish notation
Applications
right subtree
Binary Trees
RL rotation
Double Rotations
root
Basics, Mark-and-Sweep Garbage Collection
rotation
AVL
Balancing AVL Trees
double
Double Rotations
LL
Single Rotations, Removing Items from a
LL
Single Rotations, Removing Items from a
LR
Double Rotations
RL
Double Rotations
RR
Single Rotations, Removing Items from a
RR
Single Rotations, Removing Items from a
single
Double Rotations
row-major order
Array Subscript Calculations
RPN
seeReverse-Polish notation
RR rotation
Single Rotations
in a B-tree
Removing Items from a
scales
Example-Balancing Scales
scatter tables
Scatter Tables
scope
Abstract Data Types, Abstract Data Types, Scopes and Namespaces
built-in
Scopes and Namespaces
global

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 19 of 23

Scopes and Namespaces


local
Scopes and Namespaces
search interval
Locating Items in an
search tree
M-way
M-Way Search Trees
binary
Binary Search Trees
seed
Generating Random Numbers
selection sorting
Selection Sorting
selection sorts
Sorter Class Hierarchy
sentinel
Singly-Linked Lists, Adjacency Matrices
separate chaining
Separate Chaining
set
SetsMultisets, and Partitions
setter
PropertiesAccessors and Mutators
shallow copy
__copy__ Method
sibling
Terminology
sign
Floating-Point Keys
significant
Floating-Point Keys
simple cycle
More Terminology
simulated annealing
Simulated Annealing
simulation time
Discrete Event Simulation
single rotation
Double Rotations
single-ended queue
Queues
singleton
Exercises, Implementation
singly-linked list
Doubly-Linked and Circular Lists
size
Abstract Data Types
slack time
Application: Critical Path Analysis
slide
Handles
solution space
Example-Balancing Scales
solver

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 20 of 23

Abstract Backtracking Solvers


sort
topological
Topological Sort
sorted list
Ordered Lists and Sorted , Sorted Lists, Basics
sorter
Sorting and Sorters
sorting
in place
Selection Sorting
in-place
Insertion Sorting
sorting algorithm
bucket sort
Example-Bucket Sort
sorting by distribution
Distribution Sorting
sorting by exchanging
Exchange Sorting
sorting by insertion
Insertion Sorting
sorting by merging
Merge Sorting
sorting by selection
Selection Sorting
source
Exercises
spanning tree
Minimum-Cost Spanning Trees
breadth-first
Constructing Spanning Trees
depth-first
Constructing Spanning Trees
minimum
Minimum-Cost Spanning Trees
sparse graph
Sparse vs. Dense Graphs
sparse matrix
Adjacency Matrices
specializes
Class Hierarchy
stable sorts
Basics
stack
Stacks
stack frame
The Basic Axioms
state
Discrete Event Simulation
static binding
Abstract Data Types
static method
Static Methods
Stirling numbers

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 21 of 23

Partitions, Partitions
stop-and-copy garbage collection
Stop-and-Copy Garbage Collection
straight insertion sorting
Straight Insertion Sort
straight selection sorting
Straight Selection Sorting
strongly connected
Connectedness of a Directed
subgraph
Minimum-Cost Spanning Trees
minimal
Minimum-Cost Spanning Trees
subset
Comparing Sets
proper
Comparing Sets
subtraction
SetsMultisets, and Partitions
subtree
Applications
successor
Instance Attributes, More Terminology
superclass
Example-Graphical Objects
superset
Comparing Sets
proper
Comparing Sets
symbol table
HashingHash Tables, and , Applications
symmetric
Applications
symmetric difference
Exercises
tail
Singly-Linked Lists, Singly-Linked Lists
telescoping
Solving The Recurrence-Telescoping, Running Time of Divide-and-Conquer
temperature
Simulated Annealing
tertiary tree
N-ary Trees
theta
More Notation-Theta and Little
tight asymptotic bound
Tight Big Oh Bounds
time
simulation
Discrete Event Simulation
topological sort
Topological Sort
total order
Basics
binary trees

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 22 of 23

Comparing Trees
transitive
Sorted Lists, Applications, Basics
traversal
Tree Traversals, Example-Balancing Scales, Graph Traversals
breadth-first
Breadth-First Traversal, Breadth-First Traversal
breadth-first
Breadth-First Traversal, Breadth-First Traversal
depth-first
Depth-First Traversal
inorder
Inorder Traversal, Traversing a Search Tree
inorder
Inorder Traversal, Traversing a Search Tree
postorder
Postorder Traversal
preorder
Preorder Traversal
tree
Basics
N-ary
N-ary Trees
binary
Binary Trees
equivalence
Comparing Trees
expression
Expression Trees
height
More Terminology
internal path length
Successful Search
leftist
Leftist Trees
ordered
N-ary Trees, Binary Trees
ordered
N-ary Trees, Binary Trees
oriented
N-ary Trees
search
seesearch tree
tertiary
N-ary Trees
traversal
Tree Traversals
tree traversal
Applications
tuple
Associations
type
Abstract Data Types, Objects and Types
undirected arc
Undirected Graphs

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Index Page 23 of 23

undirected graph
Undirected Graphs
Unicode character set
Example
Unicode escape
Example
uniform distribution
Spreading Keys Evenly
uniform hashing model
Average Case Analysis
union
SetsMultisets, and Partitions, Basics, UnionIntersection, and Difference
union by rank
Union by Height or
union by size
Union by Size
universal set
SetsMultisets, and Partitions, Kruskal's Algorithm
unsorted list
Basics
value
Abstract Data Types, Associations, Objects and Types
Venn diagram
Alternate Representations for Trees, SetsMultisets, and Partitions
vertex
Terminology
visibility
Abstract Data Types
visitor
Visitors
weakly connected
Connectedness of a Directed
weighted path length
Shortest-Path Algorithms
word size
Middle Square Method

Copyright © 2003 by Bruno R. Preiss, P.Eng. All rights reserved.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Stacks, Queues, and Deques Page 1 of 2

Data Structures and Algorithms with Object-Oriented Design Patterns in Python

Stacks, Queues, and Deques

In this chapter we consider several related abstract data types--stacks, queues, and deques. Each of
these can be viewed as a pile of items. What distinguishes each of them is the way in which items are
added to or removed from the pile.

In the case of a stack, items are added to and removed from the top of the pile. Consider the pile of
papers on your desk. Suppose you add papers only to the top of the pile or remove them only from
the top of the pile. At any point in time, the only paper that is visible is the one on top. What you
have is a stack.

Now suppose your boss comes along and asks you to complete a form immediately. You stop doing
whatever it is you are doing, and place the form on top of your pile of papers. When you have filled-
out the form, you remove it from the top of the stack and return to the task you were working on
before your boss interrupted you. This example illustrates that a stack can be used to keep track of
partially completed tasks.

A queue is a pile in which items are added an one end and removed from the other. In this respect, a
queue is like the line of customers waiting to be served by a bank teller. As customers arrive, they
join the end of the queue while the teller serves the customer at the head of the queue. As a result, a
queue is used when a sequence of activities must be done on a first-come, first-served basis.

Finally, a deque extends the notion of a queue. In a deque, items can be added to or removed from
either end of the queue. In a sense, a deque is the more general abstraction of which the stack and the
queue are just special cases.

As shown in Figure , we view stacks, queues, and deques as containers. This chapter presents a

classes presented are extensions of the abstract Container class defined in Chapter .

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Stacks, Queues, and Deques Page 2 of 2

Figure: Object class hierarchy.

Stacks
Queues
Deques
Exercises
Projects

Copyright © 2003 by Bruno R. Preiss, P.Eng. All rights reserved.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Data Types and Abstraction Page 1 of 1

Data Structures and Algorithms with Object-Oriented Design Patterns in Python

Data Types and Abstraction

It is said that ``computer science is [the] science of abstraction[2].'' But what exactly is abstraction?
Abstraction is ``the idea of a quality thought of apart from any particular object or real thing having
that quality''[10]. For example, we can think about the size of an object without knowing what that
object is. Similarly, we can think about the way a car is driven without knowing its model or make.

Abstraction is used to suppress irrelevant details while at the same time emphasizing relevant ones.
The benefit of abstraction is that it makes it easier for the programmer to think about the problem to
be solved.

Abstract Data Types


Design Patterns
Exercises
Projects

Copyright © 2003 by Bruno R. Preiss, P.Eng. All rights reserved.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Stacks Page 1 of 2

Data Structures and Algorithms with Object-Oriented Design Patterns in Python

Stacks
The simplest of all the containers is a stack . A stack is a container which provides exactly one
method, push, for putting objects into the container; and one method, pop, for taking objects out of
the container. Figure

Figure: Basic stack operations.

Objects which are stored in a stack are kept in a pile. The last item put into the stack is a the top.
When an item is pushed into a stack, it is placed at the top of the pile. When an item popped, it is
always the top item which is removed. Since it is always the last item to be put into the stack that is
the first item to be removed, a stack is a last-in, first-out or LIFO data structure.

In addition to the push and pop operations, the typical stack implementation also has a property
called top that returns the item at the top of the stack without removing it from the stack.

Program defines the Stack class. The abstract Stack class extends the abstract Container class
defined in Program -Program . Hence, it comprises all of the methods inherited from
Container plus the push and pop methods and the Top property.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Stacks Page 2 of 2

Program: Abstract Stack class.

When implementing a data structure, the first issue to be addressed is which foundational data
structure(s) to use. Often, the choice is between an array-based implementation and a linked-list
implementation. The next two sections present an array-based implementation of stacks followed by
a linked-list implementation.

Array Implementation
Linked-List Implementation
Applications

Copyright © 2003 by Bruno R. Preiss, P.Eng. All rights reserved.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Queues Page 1 of 2

Data Structures and Algorithms with Object-Oriented Design Patterns in Python

Queues
In the preceding section we saw that a stack comprises a pile of objects that can be accessed only at
one end--the top. In this section we examine a similar data structure called a single-ended queue .
Whereas in a stack we add and remove elements at the same end of the pile, in a single-ended queue
we add elements at one end and remove them from the other. Since it is always the first item to be
first-in, first-out or FIFO data
structure. Figure

Figure: Basic queue operations.

Program defines the Queue class. The abstract Queue class extends the abstract Container class
defined in Program . Hence, it comprises all the methods inherited from Container plus the
methods, enqueue and eequeue, and the head property. As we did with stacks, we examine two
queue implementations--an array-based one and a linked-list one.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Queues Page 2 of 2

Program: Abstract Queue class.

Array Implementation
Linked-List Implementation
Applications

Copyright © 2003 by Bruno R. Preiss, P.Eng. All rights reserved.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Deques Page 1 of 2

Data Structures and Algorithms with Object-Oriented Design Patterns in Python

Deques

In the preceding section we saw that a queue comprises a pile of objects into which we insert items at
one end and from which we remove items at the other end. In this section we examine an extension

structure is a deque . The word deque is an acronym derived from double-ended queue .

Figure
head of the queue, Head, EnqueueHead and DequeueHead, and three operations to access the tail of
the queue, Tail, EnqueueTail and DequeueTail.

Figure: Basic deque operations.

Program defines the Deque class. The abstract Deque class extends the abstract Container class
defined in Program . Hence, it comprises all of the methods inherited from Container plus the
methods, enqueueHead, dequeueHead, enqueueTail, and dequeueTail, and the properties, head
and tail.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Deques Page 2 of 2

Program: Abstract Deque class.

The dequeueHead method of the Deque class is trivial to implement--it simply calls the dequeue
method inherited from the Queue class. Similarly, the enqueueTail method simply calls the
enqueue method inherited from the Queue class.

Array Implementation
Linked List Implementation
Doubly-Linked and Circular Lists

Copyright © 2003 by Bruno R. Preiss, P.Eng. All rights reserved.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Exercises Page 1 of 2

Data Structures and Algorithms with Object-Oriented Design Patterns in Python

Exercises
1. The array-based stack implementation introduced in Program
a result, it is possible for the stack to become full.
1. Rewrite the push method so that it doubles the length of the array when the array is full.
2. Rewrite the pop method so that it halves the length of the array when the array is less
than half full.
3. Show that the average time for both push and pop operations is O(1). Hint: Consider the
running time required to push items onto an empty stack, where .
2. Consider a sequence S of push and pop operations performed on a stack that is initially empty.
The sequence S is a valid sequence of operations if at no point is a pop operation attempted on
an empty stack and if the stack is empty at the end of the sequence. Design a set of rules for
generating a valid sequence.
3. Devise an implementation of the queue abstract data type using two stacks. Give algorithms
for the enqueue and dequeue operations, and derive tight big-oh expressions for the running
times of your implementation.
4. Write each of the following infix expressions in postfix notation:
1. ,
2. ,
3. ,
4. ,
5. , and
6. .
5. Write each of the following postfix expressions in infix notation:
1. ,
2. ,
3. ,
4. ,
5. , and
6. .
6. Devise an algorithm which translates a postfix expression to a prefix expression. Hint: Use a
stack of strings.
7. The array-based queue implementation introduced in Program
a result, it is possible for the queue to become full.
1. Rewrite the enqueue method so that it doubles the length of the array when the array is
full.
2. Rewrite the dequeue method so that it halves the length of the array when the array is
less than half full.
3. Show that the average time for both enqueue and dequeue operations is O(1).
8. Stacks and queues can be viewed as special cases of deques. Show how all the operations on
stacks and queues can be mapped to operations on a deque. Discuss the merits of using a
deque to implement a stack or a queue.
9. Suppose we add a new operation to the stack ADT called findMinimum that returns a

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Exercises Page 2 of 2

reference to the smallest element in the stack. Show that it is possible to provide an
implementation for findMinimum that has a worst case running time of O(1).
10. The breadth-first traversal method shown in Program
order of their levels in the tree. Modify the algorithm so that the nodes are visited in reverse.
Hint: Use a stack.

Copyright © 2003 by Bruno R. Preiss, P.Eng. All rights reserved.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Projects Page 1 of 2

Data Structures and Algorithms with Object-Oriented Design Patterns in Python

Projects
1. Enhance the functionality of the RPN calculator given in Program in the following ways:
1. Use double-precision, floating-point arithmetic.
2. Provide the complete repertoire of basic operators: +, -, , and .
3. Add an exponentiation operator and a unary negation operator.
4. Add a clear method that empties the operand stack and a print method that prints out the

2. Modify Program so that it accepts expressions written in prefix (Polish) notation. Hint: See
Exercise .
3. Write a program to convert a postfix expression into an infix
way to do this is to modify the RPN calculator program given in Program to use a stack of
infix expressions. A binary operator should pop two strings from the stack and then push a
string which is formed by concatenating the operator and its operands in the correct order. For
example, suppose the operator is ``*'' and the two strings popped from the stack are "(b+c)"
and "a". Then the result that gets pushed onto the stack is the string "a*(b+c)".
4. Devise a scheme using a stack to convert an infix expression to a postfix expression. Hint: In
a postfix expression operators appear after their operands whereas in an infix expression they
appear between their operands. Process the symbols in the prefix expression one-by-one.
Output operands immediately, but save the operators in a stack until they are needed. Pay

5. Modify your solution to Project


is, create an infixCalculator method in the style of Program .
6. Consider a string of characters, S, comprised only of the characters (, ), [, ], , and . We say
that S is balanced if it has one of the following forms:
, i.e., S is the string of length zero,
,
,
,

where both T and U are balanced strings, In other words, for every left parenthesis, bracket or
brace, there is a corresponding right parenthesis, bracket or brace. For example, "{()[()]}" is
balanced, but "([)]" is not. Write a program that uses a stack of characters to test whether a
given string is balanced.
7. Design and implement a MultipleStack class which provides stacks in a single
container. The declaration of the class should look something like this:

class MultipleStack(Container):
def __init__(self, numberOfStacks): ...
def push(self, obj, whichStack): ...
def pop(self, whichStack): ...
# ...

In addition to self, the __init__ method takes a single integer argument that specifies
the number of stacks in the container.
In addition to self, the push method takes two arguments. The first gives the object to

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Projects Page 2 of 2

be pushed and the second specifies the stack on which to push it.
In addition to self, the pop method takes a single integer argument which specifies the
stack to pop.
Choose one of the following implementation approaches:
1. Keep all the stack elements in a single array.
2. Use an array of Stack objects.
3. Use a linked list of Stack objects.
8. Design and implement a class called DequeAsDoublyLinkedList that implements the Deque
-linked list. Select one of the approaches shown in Figure .
9. In Section , the DequeAsArray class extends the QueueAsArray class. Redesign the
DequeAsArray and QueueAsArray components of the class hierarchy making DequeAsArray
the base class and deriving QueueAsArray from it.

Figure: Expression tree for .

10. Devise an approach for evaluating an arithmetic expression using a queue (rather than a stack).
Hint and then do a breadth-first
traversal of the tree in reverse (see Exercise ). For example, the expression
becomes . Evaluate the resulting sequence from left to right
using a queue in the same way that a postfix expression is evaluated using a stack.

Copyright © 2003 by Bruno R. Preiss, P.Eng. All rights reserved.

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/html/pag... 22/05/2018
Page 1 of 1

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/copyright... 22/05/2018
Page 1 of 1

mk:@MSITStore:C:\Users\shreya\Desktop\Me\python\test%20Bruno.chm::/signature... 22/05/2018

You might also like