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

Java Linked Lists PDF

Uploaded by

jeo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Java Linked Lists PDF

Uploaded by

jeo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Introduction to Linked Data Structures

Introduction to Linked Data Structures
Chapter 15
• A
A linked data structure
li k d d t t t consists of capsules of data known as 
it f l fd t k
nodes that are connected via links
Linked Data  – Links can be viewed as arrows and thought of as one way passages 
Structures f
from one node to another
d t th
• In Java, nodes are realized as objects of a node class
• The data in a node is stored via instance variables
The data in a node is stored via instance variables
• The links are realized as references
– A reference is a memory address, and is stored in a variable of a class 
type
– Therefore, a link is an instance variable of the node class type itself

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐2

Java Linked Lists


Java Linked Lists Nodes and Links in a Linked List

• The simplest kind of linked data structure is a 
h i l ki d f li k d d i
linked list
• A linked list consists of a single chain of nodes, 
y
each connected to the next by a link
– The first node is called the head node
– The last node serves as a kind of end marker
The last node serves as a kind of end marker

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐3 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐4


A Simple Linked List Class
A Simple Linked List Class A Node Class (Part 1 of 3)
A Node Class (Part 1 of 3)
• In a linked list, each node is an object of a node class
I li k d li t h d i bj t f d l
– Note that each node is typically illustrated as a box containing one or 
more pieces of data
• Each node contains data and a link to another node
– A piece of data is stored as an instance variable of the node
– Data is represented as information contained within the node "box"
p
– Links are implemented as references to a node stored in an instance 
variable of the node type
– Links are typically illustrated as arrows that point to the node to which 
yp y p
they "link"

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐5 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐6

A Node Class (Part 2 of 3)


A Node Class (Part 2 of 3) A Node Class (Part 3 of 3)
A Node Class (Part 3 of 3)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐7 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐8


A Simple Linked List Class
A Simple Linked List Class A Simple Linked List Class
A Simple Linked List Class
• Th
The first node, or start node in a linked list is called 
fi t d t t d i li k d li t i ll d • A
A linked list object contains the variable head
li k d li t bj t t i th i bl h d as an 
the head node instance variable of the class
– The
The entire linked list can be traversed by starting at the 
entire linked list can be traversed by starting at the • A linked list object does not contain all the nodes in 
A linked list object does not contain all the nodes in
head node and visiting each node exactly once the linked list directly
• There is typically a variable of the node type (e.g.,  – Rather, it uses the instance variable head
, to locate the 
) h f h f d
head) that contains a reference to the first node in  head node of the list
the linked list – The head node and every node of the list contain a link 
– However, it is not the head node, nor is it even a node
However it is not the head node nor is it even a node instance variable that provides a reference to the next
instance variable that provides a reference to the next 
– It simply contains a reference to the head node node in the list
– Therefore, once the head node can be reached, then every 
other node in the list can be reached 
th d i th li t b h d

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐9 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐10

An Empty List Is Indicated by null


An Empty List Is Indicated by null A Linked List Class (Part 1 of 6)
A Linked List Class (Part 1 of 6)

• Th
The head
h d instance variable contains a reference to 
i i bl i f
the first node in the linked list
– If the list is empty, this instance variable is set to null
If th li t i t thi i t i bl i t t ll
– Note:  This is tested using ==, not the equals method
• The
The linked list constructor sets the head instance 
linked list constructor sets the head instance
variable to null
– This indicates that the newly created linked list is empty
This indicates that the newly created linked list is empty

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐11 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐12


A Linked List Class (Part 2 of 6)
A Linked List Class (Part 2 of 6) A Linked List Class (Part 3 of 6)
A Linked List Class (Part 3 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐13 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐14

A Linked List Class (Part 4 of 6)


A Linked List Class (Part 4 of 6) A Linked List Class (Part 5 of 6)
A Linked List Class (Part 5 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐15 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐16


A Linked List Class (Part 6 of 6)
A Linked List Class (Part 6 of 6) Indicating the End of a Linked List
Indicating the End of a Linked List
• The last node in a linked list should have its 
link instance variable set to null
– That way the code can test whether or not a node 
is the last node
is the last node
– Note:  This is tested using ==, not the equals
method

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐17 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐18

Traversing a Linked List


Traversing a Linked List Traversing a Linked List
g
• If
If a linked list already contains nodes, it can be 
li k d li l d i d i b
traversed as follows:
– SSet a local variable equal to the value stored by the head 
t l l i bl l t th l t d b th h d
node (its reference)
– This will provides the location of the first node
This will provides the location of the first node
– After accessing the first node, the accessor method for the 
link instance variable will provide the location of the next 
node
– Repeat this until the location of the next node is equal to 
null

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐19 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐20


Adding a Node at the Start
Adding a Node to a Linked List
Adding a Node to a Linked List
• The method add adds a node to the start of the 
linked list
– This makes the new node become the first node on the list
• The variable head gives the location of the current 
first node of the list
– Therefore, when the new node is created, its link field is 
set equal to head
– Then head is set equal to the new node

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐21 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐22

Deleting the Head Node from a Linked  A Linked List Demonstration 
List 
Li (
(Part 1 of 3)
f )
• Th
The method deleteHeadNode
th d d l t H dN d removes the first 
th fi t
node from the linked list
– It
It leaves the head
leaves the head variable pointing to (i.e., containing a 
variable pointing to (i e containing a
reference to) the old second node in the linked list
• The deleted node will automatically be collected and 
its memory recycled, along with any other nodes that 
l d l h h d h
are no longer accessible
– In Java, this process is called automatic garbage collection
In Java this process is called automatic garbage collection

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐23 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐24


A Linked List Demonstration  A Linked List Demonstration 
(
(Part 2 of 3)
f ) (
(Part 3 of 3)
f )

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐25 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐26

Node Inner Classes


Node Inner Classes Pitfall: Privacy Leaks
Pitfall:  Privacy Leaks
• N
Note that the linked list class discussed so far is dependent on 
h h li k d li l di d f i d d • Th
The original node and linked list classes examined so 
i i l d d li k d li l i d
an external node class far have a dangerous flaw
• A linked list or similar data structure can be made self
A linked list or similar data structure can be made self‐ – Th
The node class accessor method returns a reference to a 
d l th d t f t
contained by making the node class an inner class node
• A node inner class so defined should be made private, unless  – Recall that if a method returns a reference to an instance 
Recall that if a method returns a reference to an instance
used elsewhere variable of a mutable class type, then the private
– This can simplify the definition of the node class by eliminating the  restriction on the instance variables can be easily defeated
need for accessor and mutator methods
need for accessor and mutator methods
– Since the instance variables are private, they can be accessed directly  – The easiest way to fix this problem would be to make the 
from methods of the outer class without causing a privacy leak node class a private inner class in the linked list class

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐27 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐28


A Linked List Class with a Node Inner Class (Part  A Linked List Class with a Node Inner Class (Part 
1 f 6)
1 of 6) 2 f 6)
2 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐29 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐30

A Linked List Class with a Node Inner Class (Part  A Linked List Class with a Node Inner Class (Part 
3 f 6)
3 of 6) 4 f 6)
4 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐31 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐32


A Linked List Class with a Node Inner Class (Part  A Linked List Class with a Node Inner Class (Part 
5 f 6)
5 of 6) 6 f 6)
6 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐33 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐34

A Generic Linked List Class 
A Generic Linked List
A Generic Linked List (
(Part 1 of 9)
f )
• A
A linked list can be created whose Node
li k d li t b t d h N d class has a type 
l h t
parameter T for the type of data stored in the node
– Therefore, it can hold objects of any class type, including types that 
contain multiple instance variable
t i lti l i t i bl
– The type of the actual object is plugged in for the type parameter T
• For the most part, this class can have the same methods, 
p
coded in basically the same way, as the previous linked list 
example
– The only difference is that a type parameter is used instead of an 
y yp p
actual type for the data in the node
• Other useful methods can be added as well

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐35 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐36


A Generic Linked List Class  A Generic Linked List Class 
(
(Part 2 of 9)
f ) (
(Part 3 of 9)
f )

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐37 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐38

A Generic Linked List Class  A Generic Linked List Class 
(
(Part 4 of 9)
f ) (
(Part 5 of 9)
f )

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐39 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐40


A Generic Linked List Class  A Generic Linked List Class 
(
(Part 6 of 9)
f ) (
(Part 7 of 9)
f )

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐41 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐42

A Generic Linked List Class  A Generic Linked List Class 
(
(Part 8 of 9)
f ) (
(Part 9 of 9)
f )

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐43 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐44


A Sample Class for the Data in a  A Sample Class for the Data in a 
Generic Linked List (Part 1 of 2) Generic Linked List (Part 2 of 2)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐45 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐46

A Generic Linked List Demonstration  A Generic Linked List Demonstration 
(Part 1 of 2) (Part 2 of 2)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐47 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐48


Pitfall: Using Node instead of Node<T>
Pitfall:  Using Node instead of Node<T> A Generic Linked List: the equals Method
A Generic Linked List:  the equals

• Note: This pitfall is explained by example –
N Thi i f ll i l i db l any names can  • Like other classes, a linked list class should normally have an 
Lik th l li k d li t l h ld ll h
be substituted for the node Node and its parameter <T> equals method
• When defining the LinkedList3<T> class, the type for a 
When defining the LinkedList3<T> class the type for a • The equals
q method can be defined in a number of 
node is Node<T>, not Node reasonable ways 
– Different definitions may be appropriate for  different situations 
– If the <T> is omitted, this is an error for which the compiler may or 
may not issue an error message (depending on the details of the 
i (d di h d il f h • Two such possibilities are the following:
Two such possibilities are the following:
code), and even if it does, the error message may be quite strange 1. They contain the same data entries (possibly in different orders)
– Look for a missing <T> when a program that uses nodes with type  2. They contain the same data entries in the same order
parameters gets a strange error message or doesn't run correctly • Of course, the type plugged in for T
Of th t l d i f T must also have redefined 
t l h d fi d
the equals method

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐49 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐50

An equals Method for the Linked List  An equals Method for the Linked List 


in Display 15.7 (Part 1 of 2) in Display 15.7 (Part 2 of 2)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐51 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐52


Simple Copy Constructors and clone
A Generic Linked List:  the private method 
Methods
copyOf
• Th
There is a simple way to define copy constructors and the 
i i l d fi d h • Th
The private helping method copyOf
i t h l i th d Of takes an argument that 
t k t th t
clone method for data structures such as linked lists is a reference to a head node of a linked list, and returns a 
– Unfortunately, this approach produces only shallow copies
Unfortunately, this approach produces only shallow copies reference to the head node of a copy of that list
py
• The private helping method copyOf is used by both the copy  – It goes down the argument list one node at a time and makes a copy 
constructor and the clone method of each node
– The new nodes are added to the end of the linked list being built
The new nodes are added to the end of the linked list being built
• The copy constructor uses copyOf to create a copy of the list 
of nodes • However, although this produces a new linked list with all new 
nodes, the new list is not truly independent because the data 
• The clone
The clone method first invokes its superclass clone
method first invokes its superclass clone object is not cloned
method, and then uses copyOf to create a clone of the list of 
nodes

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐53 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐54

A Copy Constructor and clone Method  A Copy Constructor and clone Method for 


for a Generic Linked List (Part 1 of 6) a Generic Linked List (Part 2 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐55 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐56


A Copy Constructor and clone Method for  A Copy Constructor and clone Method for 
a Generic Linked List (Part 3 of 6) a Generic Linked List (Part 4 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐57 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐58

A Copy Constructor and clone Method for  A Copy Constructor and clone Method for 


a Generic Linked List (Part 5 of 6) a Generic Linked List (Part 6 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐59 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐60


Pitfall:  The clone Method Is Protected in 
Object Exceptions
• It would have been preferable to clone the data  • A
A generic data structure is likely to have methods that throw 
i d i lik l h h d h h
belonging to the list being copied in the copyOf exceptions
method as follows:
method as follows: • Situations such as a null
Situations such as a null argument to the copy constructor 
argument to the copy constructor
nodeReference = new may be handled differently in different situations
Node((T)(position.data).clone(), null); – If this happens, it is best to throw a NullPointerException, and 
• However, this is not allowed, and this code will not  l h
let the programmer who is using the linked list handle the exception, 
h i i h li k d li h dl h i
rather than take some arbitrary action
compile
– A NullPointerException is an unchecked exception:  it need not 
– The
The error message generated will state that clone
error message generated will state that clone is protected 
is protected be caught or declared in a throws clause
in Object
– Although the type used is T, not Object, any class can be 
plugged in for T
plugged in for T
– When the class is compiled, all that Java knows is that T is a 
descendent class of Object

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐61 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐62

Tip:  Use a Type Parameter Bound for a Better   Tip:  Use a Type Parameter Bound for a Better  
clone clone

• One solution to this problem is to place a  • Any class that implements the 
bound on the type parameter T so that it  PubliclyCloneable interface would 
must satisfy a suitable interface h
have these three properties:
h h i
1. It would implement the Cloneable interface 
– Although there is no standard interface that does 
because PubliclyCloneable extends 
because PubliclyCloneable extends
this, it is easy to define one Cloneable
• For example, a PubliclyCloneable p p
2. It would have to implement a public clone
interface could be defined method
3. Its clone method would have to make a deep 
copy

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐63 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐64


A Generic Linked List with a Deep Copy 
The PubliclyCloneable Interface
The PubliclyCloneable
clone Method (Part 1 of 8)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐65 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐66

A Generic Linked List with a Deep Copy  A Generic Linked List with a Deep Copy 
clone Method (Part 2 of 8) clone Method (Part 3 of 8)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐67 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐68


A Generic Linked List with a Deep Copy  A Generic Linked List with a Deep Copy 
clone Method (Part 4 of 8) clone Method (Part 5 of 8)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐69 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐70

A Generic Linked List with a Deep Copy  A Generic Linked List with a Deep Copy 
clone Method (Part 6 of 8) clone Method (Part 7 of 8)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐71 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐72


A Generic Linked List with a Deep Copy 
A Linked List with a Deep Copy clone Method
A Linked List with a Deep Copy clone
clone Method (Part 8 of 8)
• Some of the details of the clone method in the previous 
linked list class may be puzzling, since the following code 
would also return a deep copy:
would also return a deep copy:
public LinkedList<T> clone()
{
return new LInkedList<T>(this);
}
• However
However, because the class implements 
because the class implements
PubliclyCloneable which, in turn, extends 
Cloneable, it must implement the Cloneable
interface as specified in the Java documentation

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐73 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐74

A PubliclyCloneable Class (Part 1 of 4)


A PubliclyCloneable Class (Part 1 of 4) A PubliclyCloneable Class (Part 2 of 4)
A PubliclyCloneable Class (Part 2 of 4)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐75 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐76


A PubliclyCloneable Class (Part 3 of 4)
A PubliclyCloneable Class (Part 3 of 4) A PubliclyCloneable Class (Part 4 of 4)
A PubliclyCloneable Class (Part 4 of 4)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐77 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐78

Demonstration of Deep Copy clone  Demonstration of Deep Copy clone 
(Part 1 of 3) (Part 2 of 3)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐79 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐80


Demonstration of Deep Copy clone  Tip:  Cloning is an "All or Nothing" 
(Part 3 of 3) Affair
• If a clone method is defined for a class, then 
g
it should follow the official Java guidelines
– In particular, it should implement the 
Cloneable interface

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐81 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐82

Iterators Iterators
• A collection of objects, such as the nodes of a linked list,  • The basic methods used by an iterator are as 
must often be traversed in order to perform some action 
on each object
j follows:
– An iterator is any object that enables a list to be traversed in this  – restart:  Resets the iterator to the beginning of 
way
• A
A linked list class may be created that has an iterator inner 
linked list class may be created that has an iterator inner the list
class – hasNext:  Determines if there is another data item 
– If iterator variables are to be used outside the linked list class, then  on the list
the iterator class would be made public
the iterator class would be made public
– The linked list class would have an iterator method that  – next:  Produces the next data item on the list
returns an iterator for its calling object
– Given a linked list named list, this can be done as follows:
Given a linked list named list, this can be done as follows:
LinkedList2.List2Iterator i = list.iterator();

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐83 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐84


A Linked List with an Iterator  A Linked List with an Iterator 
(Part 1 of 6) (Part 2 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐85 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐86

A Linked List with an Iterator  A Linked List with an Iterator 
(Part 3 of 6) (Part 4 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐87 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐88


A Linked List with an Iterator  A Linked List with an 
(Part 5 of 6) Iterator (Part 6 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐89 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐90

Using an Iterator (Part 1 of 6)


Using an Iterator (Part 1 of 6) Using an Iterator (Part 2 of 6)
Using an Iterator (Part 2 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐91 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐92


Using an Iterator (Part 3 of 6)
Using an Iterator (Part 3 of 6) Using an Iterator (Part 4 of 6)
Using an Iterator (Part 4 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐93 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐94

Using an Iterator (Part 5 of 6)


Using an Iterator (Part 5 of 6) Using an Iterator (Part 6 of 6)
Using an Iterator (Part 6 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐95 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐96


The Java Iterator Interface
The Java Iterator Interface Adding and Deleting Nodes
Adding and Deleting Nodes
• Java has an interface named Iterator that  • An iterator is normally used to add or delete a node 
p
specifies how Java would like an iterator to  in a linked list
behave • Given iterator variables position and previous, 
the following two lines of code will delete the node 
– Although the iterators examined so far do not 
Although the iterators examined so far do not
at location position:
satisfy this interface, they could be easily 
previous.link = position.link;
redefined to do so
redefined to do so position = position.link;
– Note:  previous points to the node before position

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐97 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐98

Deleting a Node (Part 1 of 2)


Deleting a Node (Part 1 of 2) Deleting a Node (Part 2 of 2)
Deleting a Node (Part 2 of 2)
3. Update
p t o to reference the next node
position
pos
1. Existing list with the iterator positioned at “shoes” position = position.link;
"coat" "orange juice" "shoes" "socks" null
"coat" "orange juice" "shoes" "socks " null

head previous position


head previous position

Since no variable references the node "shoes" Java will automatically


2. Bypass the node at position from previous recycle the memory allocated for it .
previous.link = position.link;

"coat" "orange juice" "shoes" "socks" null 4. Same picture with deleted node not shown
"coat" "orange juice" "socks" null
head previous position

head previous position

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐99 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐100


Adding a Node between Two 
Adding and Deleting Nodes
Adding and Deleting Nodes
Nodes (Part 1 of 2)
• Note that Java has automatic garbage collection
N h J h i b ll i 1. Existing list with the iterator positioned at “shoes”
– In many other languages the programmer has to keep track of deleted  "coat" "orange juice" "shoes" null

nodes and explicitly return their memory for recycling
head previous position
– This procedure is called explicit memory management
• The iterator variables position and previous can be 
used to add a node as well
used to add a node as well 2 Create new Node with "socks" linked to "shoes"
2.

– previous will point to the node before the insertion point, and  temp = new Node(newData, position); // newData is "socks"

position will point to the node after the insertion point "coat" "orange juice" "shoes" null

Node temp = new Node(newData,position); head previous position

previous.link = temp;
t
temp "
"socks"
k "

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐101 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐102

Adding a Node between Two 
Variations on a Linked List
Variations on a Linked List
Nodes (Part 2 of 2)
3. Make previous link to the Node temp • An ordinary linked list allows movement in one direction only
An ordinary linked list allows movement in one direction only
previous.link = temp;
• However, a doubly linked list has one link that references the next node, 
and one that references the previous node
"coat"
coat "orange
orange juice
juice" "shoes"
shoes null
• The node class for a doubly linked list can begin as follows:
The node class for a doubly linked list can begin as follows:
head previous position private class TwoWayNode
{
private String item;
"socks"
temp private TwoWayNode previous;
private TwoWayNode next;
. . .
4. Picture redrawn for clarity, but structurally identical to picture 3
• In addition, the constructors and methods in the doubly linked list class 
"coat" "orange juice" "socks " "shoes" null would be modified to accommodate the extra link
head previous temp position

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐103 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐104


A Doubly Linked List Adding a Node to the Front of a 
Doubly Linked List

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐105 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐106

Deleting a  Node from a Doubly  Deleting a  Node from a Doubly 
Linked List (1 of 2) Linked List (2 of 2)
1. Existing list with an iterator referencing "shoes" 3. Bypass the "shoes" node from the previous link of the next node
and move position off the deleted node
null "coat" "shoes” "socks” null p
position.next.previous
p = p
position.previous;
p ;
position = position.next;
head position

null "coat" "shoes”


"shoes "socks”
"socks null

2. Bypass the "shoes" node from the next link of the previous node head position
position.previous.next = position.next;

4. Picture redrawn for clarity with the "shoes" node removed since
null "coat" "shoes” "socks” null there are no longer references pointing to this node .
null "coat" "socks”
head position

head position

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐107 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐108


Inserting a Node Into a Doubly  Inserting a Node Into a Doubly 
Linked List (1 of 2) Linked List (2 of 2)
1. Existing list with an iterator referencing "shoes"

null "coat" "shoes” "socks” null

head position

2. Create new TwoWayNode with previous linked to "coat" and next to "shoes"
TwoWayNode temp = new TwoWayNode(newData, position.previous, position);
// newData = "shirt"

null "coat" "shoes” "socks” null

head
"shirt"

temp position

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐109 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐110

The Stack Data Structure


The Stack Data Structure The Queue Data Structure
The Queue Data Structure
• A stack data structure is not necessarily a  • A
A queue is a data structure that handles data in a 
i d t t t th t h dl d t i
first‐in/first‐out fashion (FIFO) like a line at a bank
p
linked data structure, but can be implemented  – Customers
Customers add themselves to the end of the line and are 
add themselves to the end of the line and are
as one served from the front of the line
• A queue can be implemented with a linked list
– A stack is a data structure that removes items in 
A stack is a data structure that removes items in
– However, a queue needs a pointer at both the head and 
the reverse order of which they were inserted  tail (the end) of the linked list
(LIFO: Last In First Out)
(LIFO:  Last In First Out) – Nodes are removed from the front
Nodes are removed from the front (head end), and are 
(head end) and are
added to the back ( tail end)
– A linked list that inserts and deletes only at the 
h d f th li t i
head of the list is a stack
t k

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐111 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐112


A Queue Class (Part 1 of 5)
A Queue Class (Part 1 of 5) A Queue Class (Part 2 of 5)
A Queue Class (Part 2 of 5)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐113 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐114

A Queue Class (Part 3 of 5)


A Queue Class (Part 3 of 5) A Queue Class (Part 4 of 5)
A Queue Class (Part 4 of 5)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐115 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐116


Demonstration of the Queue Class 
A Queue Class (Part 5 of 5)
A Queue Class (Part 5 of 5)
(Part 1 of 2)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐117 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐118

Demonstration of the Queue Class 
Running Times
Running Times
(Part 2 of 2)
• How fast is program?
H f i ?
– "Seconds"?
– Consider: large input? .. small input?
C id l i ? ll i ?
• Produce "table" 
– Based on input size
d i i
– Table called "function" in math
• With arguments and return values!
With arguments and return values!
– Argument is input size:
T(10), T(10,000), …
( ) ( )
• Function T is called "running time"

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐119 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.. 19‐120


Table for Running Time Function: 
Display 15 31 Some Values
Display 15.31  Some Values  Consider Sorting Program
Consider Sorting Program
of a Running Time Function
• Faster on smaller input set?
– Perhaps
p
– Might depend on "state" of set
• "Mostly"
Mostly  sorted already?
sorted already?
• Consider worst‐case running time
– T(N) is time taken by "hardest" list
• List that takes longest to sort

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.. 19‐121 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.. 19‐122

Counting Operations
Counting Operations Counting Operations Example
Counting Operations Example
• T(N) given by formula, such as: • iint i = 0;
i 0
Boolean found = false;
( )
T(N) = 5N + 5 (( )
while (( i < N) && !found) )
if (a[I] == target)
– "On inputs of size N program runs for found = true;
5N + 5 time units"
5N + 5 time units else
i++;
• Must be "computer‐independent"
• 5 operations per loop iteration:
p p p
– Doesn’t matter how "fast" computers are <, &&, !, [ ], ==, ++
– Can’t count "time" • After N iterations, final three: <, &&, !
• So: 6N+5 operations when target not found
– Instead count "operations"

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.. 19‐123 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.. 19‐124


Big O Notation
Big‐O Notation Big O Terminology
Big‐O Terminology
• Recall: 6N+5 operations in "worst‐case" • Linear running time:
i i i
• Expressed in "Big‐O" notation – O(N)—directly proportional to input size N
– Some constant "c" factor where • Quadratic running time:
c(6N+5) is actual running time – O(N2) 
)
• c different on different systems
– We say code runs in time O(6N+5)
• Logarithmic running time:
– But typically only consider "highest term"
– O(log N)
O(l N)
• Term with highest exponent
• Typically "log base 2"
• Very fast algorithms!
V f t l ith !
– O(N) here

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.. 19‐125 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.. 19‐126

Display 15.32  
Comparison of Running Times
Efficiency of Linked Lists
Efficiency of Linked Lists
• Find method for linked list
– May have to search entire list
y
– On average would expect to search half of the list, 
or n/2
or n/2
– In big‐O notation, this is O(n)
• Adding to a linked list
– When adding to the start we only reassign some 
g y g
references
– Constant time or O(1)
Constant time or O(1)
Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.. 19‐127 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐128
Hash Tables
Hash Tables Simple Hash Function for Strings
Simple Hash Function for Strings
• A hash table or hash map is a data structure  • SSum the ASCII value of every character in the 
th ASCII l f h t i th
y
that efficiently stores and retrieves data from  string and then compute the modulus of the 
memory sum using the size of the fixed array.  
• Here we discuss a hash table that uses an 
Here we discuss a hash table that uses an private int computeHash(String s)
{
array in combination with singly linked lists int hash = 0;
for (int i = 0; i < s.length(); i++)
{
• Uses a hash function hash += s.charAt(i);
}
– Maps an object to a key
Maps an object to a key return hash % SIZE; // SIZE = 10 in example
}
– In our example, a string to an integer
Example: “dog” = ASCII 100, 111, 103
Hash = (100 + 111 + 103) % 10 = 4
Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.. 17‐129 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.. 17‐130

Hash Table Idea


Hash Table Idea Constructing a Hash Table (1 of 2)
Constructing a Hash Table (1 of 2)
• Storage
1. Existing hash table initialized with ten empty linked lists
– Make an array of fixed size, say 10 hashArray = new LinkedList3[SIZE]; // SIZE = 10
– In each array element store a linked list
h l l k dl 0 1 2 3 4 5 6 7 8 9
hashArray empty empty empty empty empty empty empty empty empty empty
– To add an item, map (i.e. hash) it to one of the 10 
array elements, then add it to the linked list at  2. After adding "cat" with hash of 2
that location 0 1 2 3 4 5 6 7 8 9
hashArray empty empty empty empty null empty empty empty empty
• Retrieval
– To look up an item, determine its hash code then 
To look up an item determine its hash code then catt

search the linked list at the corresponding array 
slot for the item
slot for the item
Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.. 17‐131 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐132
Constructing a Hash Table (2 of 2)
Constructing a Hash Table (2 of 2) A Hash Table Class (1 of 3)
A Hash Table Class (1 of 3)
1 public class HashTable
3 After adding "dog"
3. dog with hash of 4 and "bird"
bird with hash of 7 2 {
3 // Uses the generic LinkedList2 class from Display 15.7
0 1 2 3 4 5 6 7 8 9 4 private LinkedList2[] hashArray;
5 private static final int SIZE = 10;
hashArray empty empty empty empty empty empty empty

6 public HashTable()
7 {
cat dog bird
8 hashArray = new LinkedList2[SIZE];
9 for (
(int i=0;
; i < SIZE;
; i++)
)
4. After adding "turtle" with hash of 2 – collision and chained to linked list with "cat" 10 hashArray[i] = new LinkedList2();
11 }
0 1 2 3 4 5 6 7 8 9
hashArray empty empty empty empty empty empty empty 12 private int computeHash(String
p p ( g s)
)
13 {
14 int hash = 0;
turtle dog bird 15 for (int i = 0; i < s.length(); i++)
16 {
17 hash += s.charAt(i);
cat 18 }
19 return hash % SIZE;
20 }

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐133 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐134

A Hash Table Class (2 of 3)


A Hash Table Class (2 of 3) A Hash Table Class (3 of 3)
A Hash Table Class (3 of 3)
21 /** 33 /**
22 Returns true if the target
g is in the hash table,
, 34 Stores or p
puts stringg s into the hash table
23 false if it is not. 35 */
24 */ 36 public void put(String s)
25 public boolean containsString(String target) 37 {
26 { 38 int hash = computeHash(s);
p ( ); // Get hash value
27 int hash = computeHash(target); 39 LinkedList2 list = hashArray[hash];
28 LinkedList2 list = hashArray[hash]; 40 if (!list.contains(s))
29 if (list.contains(target)) 41 {
30 return true;
; 42 // Onlyy add the target
g if it's not already
y
31 return false; 43 // on the list.
32 } 44 hashArray[hash].addToStart(s);
45 }
46 }
47 } // End HashTable class

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐135 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐136


Hash Table Demonstration (1 of 2)
Hash Table Demonstration (1 of 2) Hash Table Demonstration (2 of 2)
Hash Table Demonstration (2 of 2)
1 public class HashTableDemo 19 System.out.println("Contains fish? " +
2 { 20 h.containsString("fish"));
g( ));
3 public static void main(String[] args) 21 System.out.println("Contains cow? " +
4 { 22 h.containsString("cow"));
5 HashTable h = new HashTable(); 23 }
24 }
6 System.out.println("Adding dog, cat, turtle, bird");
7 h.put("dog");
8 h.put("cat");
9 h.put("turtle");
p ( );
SAMPLE DIALOGUE
10 h.put("bird");
11 System.out.println("Contains dog? " + Adding dog, cat, turtle, bird
12 h.containsString("dog")); Contains dog? true
13 System.out.println("Contains
y p ( cat? " + Contains cat? true
14 h.containsString("cat")); Contains turtle? true
15 System.out.println("Contains turtle? " + Contains bird? true
16 h.containsString("turtle")); Contains fish? false
17 System.out.println("Contains
y p ( bird? " + Contains cow? false
18 h.containsString("bird"));

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐137 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐138

Hash Table Efficiency


Hash Table Efficiency Set Template Class
Set Template Class
• Worst Case
– Every item inserted into the table has the same hash key,  • A set is a collection of elements in which no 
the find operation may have to search through all items  element occurs more than once
every time (same performance as a linked list, O(n) to find)
( ( ) )
• Best Case
• We can implement a simple set that uses a 
– Every item inserted into the table has a different hash key,  linked list to store the items in the set
linked list to store the items in the set
the find operation will only have to search a list of size 1,  • Fundamental set operations we will support:
very fast, O(1) to find.
f t O(1) t fi d
– Add
• Can decrease the chance of collisions with a better 
– Contains
hash function
– Union
• Tradeoff:  Lower chance of collision with bigger hash 
table, but more wasted memory space – Intersection
Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.. 17‐139 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved.. 17‐140
Sets Using Linked Lists
Sets Using Linked Lists A Set Class (1 of 5)
A Set Class (1 of 5)
1 // Uses a linked list as the internal data structure
2 // to store items in a set.
3 public class Set<T>
4 {
5 private class Node<T>
6 {
7 private T data;
8 private Node<T> link;

9 public Node(
p ( )
10 {
11 data = null;
12 link = null;
13 }
14 public Node(T newData, Node<T> linkValue)
15 {
16 data = newData;
17 link = linkValue;
;
18 }
19 }//End of Node<T> inner class

20 private Node<T> head;


p

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐141 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐142

A Set Class (2 of 5)
A Set Class (2 of 5) A Set Class (3 of 5)
A Set Class (3 of 5)
21 public Set() 39 public boolean contains(T item)
22 { 40 {
23 head = null; 41 Node<T> position = head;
24 } 42 T itemAtPosition;
25 /** 43 while (position != null)
26 Add a new item to the set. If the item 44 {
27 is already in the set, false is returned, 45 itemAtPosition = position.data;
28 otherwise true is returned. 46 if (itemAtPosition.equals(item))
29 */ 47 return true;
30 public boolean add(T
p ( newItem)) 48 position = position.link;
31 { 49 }
32 if (!contains(newItem)) 50 return false; //target was not found
33 { 51 }
34 head = new Node<T>(newItem,
( , head);
);
35 return true; 52 public void output( )
36 } 53 {
37 return false; 54 Node position = head;
38 } 55 while (position != null)
56 {
57 System.out.print(position.data.toString() + " ");
58 position = position.link;
59 }
60 System.out.println();
61 }
Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐143 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐144
A Set Class (4 of 5)
A Set Class (4 of 5) A Set Class (5 of 5)
A Set Class (5 of 5)
62 /** 86 /**
63 Returns a new set that is the union 87 Returns a new that is the intersection
64 of this set and the input set. 88 of this set and the input set.
65 */ 89 */
66 public Set<T> union(Set<T> otherSet) 90 public Set<T> intersection(Set<T> otherSet)
67 { 91 {
68 Set<T> unionSet = new Set<T>(); 92 Set<T> interSet = new Set<T>();
69 // Copy this set to unionSet 93 // Copy only items in both sets
70 Node<T> position = head; 94 Node<T> position = head;
71 while (position != null) 95 while (position != null)
72 { 96 {
73 unionSet.add(position.data); 97 if (otherSet.contains(position.data))
74 position = position.link; 98 interSet.add(position.data);
75 } 99 position = position.link;
76 // Copy otherSet items to unionSet. 100 }
77 // The add method eliminates any duplicates. 101 return interSet;
78 position = otherSet.head; 102 }
79 while (position != null) 103 }
80 {
81 unionSet.add(position.data); The clear, size, and isEmpty methods are identicalto those in Display 15.8
82 position = position.link; for the LinkedList3 class.
83 }
84 return unionSet;
85 }
Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐145 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐146

A Set Class Demo (1 of 3)
( ) A Set Class Demo (2 of 3)
A Set Class Demo (2 of 3)
1 class SetDemo
2 { 23 System.out.println("ball in set round? " +
3 public static void main(String[] args) 24 round.contains("ball"));
4 { 25 System.out.println("ball in set green? " +
5 // Round things 26 green.contains("ball"));
6 Set round = new Set<String>();
7 // Green things 27 System.out.println("ball and peas in same set? " +
8 Set green = new Set<String>(); 28 ((round.contains("ball") &&
29 (round.contains("peas"))) ||
9 // Add some data to both sets 30 (green.contains("ball") &&
10 round.add("peas"); 31 (green.contains("peas")))));
11 round.add("ball");
d dd( b ll )
12 round.add("pie"); 32 System.out.println("pie and grass in same set? " +
13 round.add("grapes"); 33 ((round.contains("pie") &&
34 (round.contains("grass"))) ||
14 green.add("peas");
dd( ) 35 (green.contains("pie") &&
15 green.add("grapes"); 36 (green.contains("grass")))));
16 green.add("garden hose");
17 green.add("grass");

18 System.out.println("Contents of set round: ");


19 round.output();
20 System.out.println("Contents of set green: ");
21 green.output();
t t()
22 System.out.println();
Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐147 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐148
A Set Class Demo (3 of 3)
A Set Class Demo (3 of 3) Trees
37 System.out.print("Union of green and round: ");
38 round.union(green).output();
39
40
System.out.print("Intersection of green and round: ");
round.intersection(green).output();
• TTrees are a very important and widely used data 
i d id l dd
41
42 }
} structure
• Like linked lists, they are a structure based on nodes 
Lik li k d li h b d d
SAMPLE DIALOGUE and links, but are more complicated than linked lists
Contents of set round: – All
All trees have a node called the root
t h d ll d th t
grapes pie ball peas
Contents of set green:
– Each node in a tree can be reached by following the links 
Grass garden hose grapes peas from the root to the node
from the root to the node
ball in set round? true – There are no cycles in a tree:  Following the links will 
ball in set green? false
ball and peas in same set? true
always lead to an "end"
pie and grass in same set? false
Union of green and round: garden hose grass peas ball pie grapes
Intersection of green and round: peas grapes

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐149 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐150

A Binary Tree (Part 1 of 2)
Trees
• A binary tree is the most common kind of tree
A bi t i th t ki d f t
– Each node in a binary tree has exactly two link instance variables
– A binary tree must satisfy the Binary Search Tree Storage Rule
• The root of the tree serves a purpose similar to that of the 
instance variable head in a linked list
– The
The node whose reference is in the root
node whose reference is in the root instance variable is called 
instance variable is called
the root node
• The nodes at the "end" of the tree are called leaf nodes
– Both of the link instance variables in a leaf node are null
Both of the link instance variables in a leaf node are null

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐151 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐152


A Binary Tree (Part 2 of 2)
A Binary Tree (Part 2 of 2) Binary Search Tree Storage Rule
Binary Search Tree Storage Rule
1. All the values in the left subtree must be less than 
the value in the root node
2. All the values in the right subtree must be greater 
than or equal to the value in the root node
3. This rule is applied recursively to each of the two 
sub ees
subtrees
(The base case for the recursion is an empty tree)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐153 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐154

Tree Properties
Tree Properties Preorder Processing
Preorder Processing
• Note that a tree has a recursive structure
N h h i 1. Process the data in the root node
– Each tree has two subtrees whose root nodes are the 
nodes pointed to by the leftLink and rightLink
nodes pointed to by the leftLink and rightLink of  of 2. Process the left subtree
Process the left subtree
the root node
3. Process the right subtree
– This makes it possible to process trees using recursive 
p p g
algorithms
• If the values of a tree satisfying the Binary Search 
Tree Storage Rule are output using Inorder 
Processing, then the values will be output in order 
f
from smallest to largest
ll t t l t

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐155 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐156


Inorder Processing
Inorder Processing Postorder Processing
Postorder Processing
1. Process the left subtree 1. Process the left subtree
2. Process the data in the root node
Process the data in the root node 2. Process the right subtree
Process the right subtree
3. Process the right subtree 3. Process the data in the root node

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐157 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐158

A Binary Search Tree for Integers (Part  A Binary Search Tree for Integers (Part 
1 of 6) 2 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐159 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐160


A Binary Search Tree for Integers (Part  A Binary Search Tree for Integers (Part 
3 of 6) 4 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐161 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐162

A Binary Search Tree for Integers (Part  A Binary Search Tree for Integers (Part 
5 of 6) 6 of 6)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐163 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐164


Demonstration Program for the Binary  Demonstration Program for the Binary 
Search Tree (Part 1 of 3) Search Tree (Part 2 of 3)

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐165 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐166

Demonstration Program for the Binary 
Efficiency of Binary Search Trees
Efficiency of Binary Search Trees
Search Tree (Part 3 of 3)
• A Binary search trees that is as short as possible can 
be processed most efficiently
– A short tree is one where all paths from root to a leaf differ 
by at most one node
• When this is so, the search method isInSubtree
is about as efficient as the binary search on a sorted 
array
– Its worst‐case running time is O(log n), where n is the 
number of nodes in the tree

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐167 Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐168


Efficiency of Binary Search Trees
Efficiency of Binary Search Trees
• A
As a tree becomes more tall and thin, this efficiency 
b ll d hi hi ffi i
falls off 
– IIn the worst case, it is the same as that of searching a 
th t it i th th t f hi
linked list with the same number of nodes
• Maintaining
Maintaining a tree so that it remains short and fat, as 
a tree so that it remains short and fat as
nodes are added, is known as balancing the tree
– A tree maintained in this manner is called a balanced tree
A tree maintained in this manner is called a balanced tree

Copyright © 2012 Pearson Addison‐Wesley. All rights reserved. 15‐169

You might also like