Java Linked Lists PDF
Java Linked Lists PDF
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
• 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
• 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
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
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)
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
A Generic Linked List Class A Generic Linked List Class
(
(Part 4 of 9)
f ) (
(Part 5 of 9)
f )
A Generic Linked List Class A Generic Linked List Class
(
(Part 8 of 9)
f ) (
(Part 9 of 9)
f )
A Generic Linked List Demonstration A Generic Linked List Demonstration
(Part 1 of 2) (Part 2 of 2)
• 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
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
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)
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)
Demonstration of Deep Copy clone Demonstration of Deep Copy clone
(Part 1 of 3) (Part 2 of 3)
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();
A Linked List with an Iterator A Linked List with an Iterator
(Part 3 of 6) (Part 4 of 6)
"coat" "orange juice" "shoes" "socks" null 4. Same picture with deleted node not shown
"coat" "orange juice" "socks" null
head previous position
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.link = temp;
t
temp "
"socks"
k "
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
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
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
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"
head
"shirt"
temp position
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"
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"
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
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 }
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
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");
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
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
A Binary Search Tree for Integers (Part A Binary Search Tree for Integers (Part
1 of 6) 2 of 6)
A Binary Search Tree for Integers (Part A Binary Search Tree for Integers (Part
5 of 6) 6 of 6)
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‐169