Download presentation
Presentation is loading. Please wait.
1
17 Data Structures
2
Much that I bound, I could not free; Much that I freed returned to me.
Lee Wilson Dodd ‘Will you walk a little faster?’ said a whiting to a snail, ‘There’s a porpoise close behind us, and he’s treading on my tail.’ Lewis Carroll There is always room at the top. Daniel Webster Push on—keep moving. Thomas Morton I’ll turn over a new leaf. Miguel de Cervantes
3
OBJECTIVES In this chapter you will learn:
To form linked data structures using references, self-referential classes and recursion. The type-wrapper classes that enable programs to process primitive data values as objects. To use autoboxing to convert a primitive value to an object of the corresponding type-wrapper class. To use auto-unboxing to convert an object of a type-wrapper class to a primitive value. To create and manipulate dynamic data structures, such as linked lists, queues, stacks and binary trees. Various important applications of linked data structures. How to create reusable data structures with classes, inheritance and composition.
4
17.1 Introduction 17.2 Type-Wrapper Classes for Primitive Types 17.3 Autoboxing and Auto-Unboxing 17.4 Self-Referential Classes 17.5 Dynamic Memory Allocation 17.6 Linked Lists 17.7 Stacks 17.8 Queues 17.9 Trees 17.10 Wrap-Up
5
17.1 Introduction Dynamic data structures Linear data structures
Linked lists Stacks Queues Binary trees
6
17.2 Type-Wrapper Classes for Primitive Types
In package java.lang Enable programmers to manipulate primitive-type values as objects Boolean, Byte, Character, Double, Float, Integer, Long and Short
7
17.3 Autoboxing and Auto-Unboxing
Boxing conversion Converts a value of a primitive type to an object of the corresponding type-wrapper class Unboxing conversion Converts an object of a type-wrapper class to a value of the corresponding primitive type J2SE 5.0 automatically performs these conversions Called autoboxing and auto-unboxing
8
17.4 Self-Referential Classes
Contains an instance variable that refers to another object of the same class type That instance variable is called a link A null reference indicates that the link does not refer to another object Illustrated by a backslash in diagrams
9
Fig. 17.1 | Self-referential-class objects linked together.
10
17.5 Dynamic Memory Allocation
The ability for a program to obtain more memory space at execution time to hold new nodes and to release space no longer needed Java performs automatic garbage collection of objects that are no longer referenced in a program Node nodeToAdd = new Node( 10 ); Allocates the memory to store a Node object and returns a reference to the object, which is assigned to nodeToAdd Throws an OutOfMemoryError if insufficient memory is available
11
17.6 Linked Lists Linked list Linear collection of nodes
Self-referential-class objects connected by reference links Can contain data of any type A program typically accesses a linked list via a reference to the first node in the list A program accesses each subsequent node via the link reference stored in the previous node Are dynamic The length of a list can increase or decrease as necessary Become full only when the system has insufficient memory to satisfy dynamic storage allocation requests
12
Performance Tip 17.1 An array can be declared to contain more elements than the number of items expected, but this wastes memory. Linked lists provide better memory utilization in these situations. Linked lists allow the program to adapt to storage needs at runtime.
13
Performance Tip 17.2 Insertion into a linked list is fast—only two references have to be modified (after locating the insertion point). All existing node objects remain at their current locations in memory.
14
Performance Tip 17.3 Insertion and deletion in a sorted array can be time consuming—all the elements following the inserted or deleted element must be shifted appropriately.
15
17.6 Linked Lists (Cont.) Singly linked list Doubly linked list
Each node contains one reference to the next node in the list Doubly linked list Each node contains a reference to the next node in the list and a reference to the previous node in the list java.util’s LinkedList class is a doubly linked list implementation
16
Performance Tip 17.4 Normally, the elements of an array are contiguous in memory. This allows immediate access to any array element, because its address can be calculated directly as its offset from the beginning of the array. Linked lists do not afford such immediate access to their elements—an element can be accessed only by traversing the list from the front (or from the back in a doubly linked list).
17
Fig. 17.2 | Linked list graphical representation.
18
Outline (1 of 6) Field data can refer to any object
List.java (1 of 6) Field data can refer to any object Stores a reference to the next ListNode object in the linked list
19
Outline (2 of 6) References to the first and last ListNodes in a List
List.java (2 of 6) References to the first and last ListNodes in a List Call one-argument constructor
20
Outline Initialize both references to null List.java (3 of 6)
21
Outline List.java (4 of 6)
22
Outline List.java (5 of 6) Predicate method that determines whether the list is empty
23
Outline Display the list’s contents (6 of 6)
List.java (6 of 6) Display a message indicating that the list is empty Output a string representation of current.data Move to the next node in the list
24
Outline EmptyListException .java
25
Outline ListTest.java (1 of 3) Insert objects at the beginning of the list using method insertAtFront Insert objects at the end of the list using method insertAtBack JVM autoboxes each literal value in an Integer object
26
Outline Deletes objects from the front of the list using method removeFromFront ListTest.java (2 of 3) Delete objects from the end of the list using method removeFromBack Call List method print to display the current list contents Exception handler for EmptyListException
27
Outline ListTest.java (3 of 3)
28
17.6 Linked Lists (Cont.) Method insertAtFront’s steps
Call isEmpty to determine whether the list is empty If the list is empty, assign firstNode and lastNode to the new ListNode that was initialized with insertItem The ListNode constructor call sets data to refer to the insertItem passed as an argument and sets reference nextNode to null If the list is not empty, set firstNode to a new ListNode object and initialize that object with insertItem and firstNode The ListNode constructor call sets data to refer to the insertItem passed as an argument and sets reference nextNode to the ListNode passed as argument, which previously was the first node
29
Fig. 17.6 | Graphical representation of operation insertAtFront.
30
17.6 Linked Lists (Cont.) Method insertAtBack’s steps
Call isEmpty to determine whether the list is empty If the list is empty, assign firstNode and lastNode to the new ListNode that was initialized with insertItem The ListNode constructor call sets data to refer to the insertItem passed as an argument and sets reference nextNode to null If the list is not empty, assign to lastNode and lastNode.nextNode the reference to the new ListNode that was initialized with insertItem The ListNode constructor sets data to refer to the insertItem passed as an argument and sets reference nextNode to null
31
Fig. 17.7 | Graphical representation of operation insertAtBack.
32
17.6 Linked Lists (Cont.) Method removeFromFront’s steps
Throw an EmptyListException if the list is empty Assign firstNode.data to reference removedItem If firstNode and lastNode refer to the same object, set firstNode and lastNode to null If the list has more than one node, assign the value of firstNode.nextNode to firstNode Return the removedItem reference
33
Fig. 17.8 | Graphical representation of operation removeFromFront.
34
17.6 Linked Lists (Cont.) Method removeFromBack’s steps
Throws an EmptyListException if the list is empty Assign lastNode.data to removedItem If the firstNode and lastNode refer to the same object, set firstNode and lastNode to null If the list has more than one node, create the ListNode reference current and assign it firstNode “Walk the list” with current until it references the node before the last node The while loop assigns current.nextNode to current as long as current.nextNode is not lastNode
35
17.6 Linked Lists (Cont.) Assign current to lastNode
Set current.nextNode to null Return the removedItem reference
36
Fig. 17.9 | Graphical representation of operation removeFromBack.
37
17.7 Stacks Stacks Last-in, first-out (LIFO) data structure
Method push adds a new node to the top of the stack Method pop removes a node from the top of the stack and returns the data from the popped node Program execution stack Holds the return addresses of calling methods Also contains the local variables for called methods Used by the compiler to evaluate arithmetic expressions
38
17.7 Stacks (Cont.) Stack class that inherits from List
Stack methods push, pop, isEmpty and print are performed by inherited methods insertAtFront, removeFromFront, isEmpty and print push calls insertAtFront pop calls removeFromFront isEmpty and print can be called as inherited Other List methods are also inherited Including methods that should not be in the stack class’s public interface
39
Outline Class StackInheritance extends class List
StackInheritance .java Method push calls inherited method insertAtFront Method pop calls inherited method removeFromFront
40
Outline (1 of 3) Create a StackInheritenace object
StackInheritance Test.java (1 of 3) Create a StackInheritenace object Push integers onto the stack
41
Outline Pop the objects from the stack in an infinite while loop
StackInheritance Test.java (2 of 3) Implicitly call inherited method print Display the exception’s stack trace
42
Outline StackInheritance Test.java (3 of 3)
43
17.7 Stacks (Cont.) Stack class that contains a reference to a List
Enables us to hide the List methods that should not be in our stack’s public interface Each stack method invoked delegates the call to the appropriate List method method push delegates to List method insertAtFront method pop delegates to List method removeFromFront method isEmpty delegates to List method isEmpty method print delegates to List method print
44
Outline private List reference (1 of 2)
StackComposition .java (1 of 2) push method delegates call to List method insertAtFront
45
Outline Method pop delegates call to List method removeFromFront
StackComposition .java (2 of 2) Method isEmpty delegates call to List method isEmpty Method print delegates call to List method print
46
17.8 Queues Queue Similar to a checkout line in a supermarket
First-in, first-out (FIFO) data structure Enqueue inserts nodes at the tail (or end) Dequeue removes nodes from the head (or front) Used to support print spooling A spooler program manages the queue of printing jobs
47
17.8 Queues (Cont.) Queue class that contains a reference to a List
Method enqueue calls List method insertAtBack Method dequeue calls List method removeFromFront Method isEmpty calls List method isEmpty Method print calls List method print
48
Outline An object of class List (1 of 2)
Queue.java (1 of 2) Method enqueue calls List method insertAtBack
49
Outline Method dequeue calls List method removeFromFront (2 of 2)
Queue.java (2 of 2) Method isEmpty calls List method isEmpty Method print calls List method print
50
Outline (1 of 3) Create a Queue object Enqueue four integers
QueueTest.java (1 of 3) Create a Queue object Enqueue four integers
51
Outline Dequeue the objects in first-in, first-out order (2 of 3)
Queue.java (2 of 3) Display the exception’s stack trace
52
Outline QueueTest.java (3 of 3)
53
17.9 Trees Trees The root node is the first node in a tree
Each link refers to a child Left child is the root of the left subtree Right child is the root of the right subtree Siblings are the children of a specific node A leaf node has no children
54
17.9 Trees (Cont.) Binary search trees Traversing a tree
Values in the left subtree are less than the value in that subtree’s parent node and values in the right subtree are greater than the value in that subtree’s parent node Traversing a tree Inorder - traverse left subtree, then process root, then traverse right subtree Preorder - process root, then traverse left subtree, then traverse right subtree Postorder - traverse left subtree, then traverse right subtree, then process root
55
Fig. 17.15 | Binary tree graphical representation.
56
Fig. 17.16 | Binary search tree containing 12 values.
57
Outline (1 of 5) Declare left child, node value and right child
Tree.java (1 of 5) Declare left child, node value and right child
58
Outline Allocate a new TreeNode and assign it to reference leftNode
Tree.java (2 of 5) Allocate a new TreeNode and assign it to reference rightNode
59
Outline TreeNode reference to the root node of the tree (3 of 5)
Tree.java (3 of 5) Allocate a new TreeNode and assign it to reference root Call TreeNode method insert Call Tree helper method preorderHelper
60
Outline Tree.java (4 of 5) Call Tree helper method inorderHelper
61
Outline Call Tree helper method postorderHelper Tree.java (5 of 5)
62
Outline (1 of 2) Create a Tree object Insert values into tree
TreeTest.java (1 of 2) Create a Tree object Insert values into tree
63
Outline TreeTest.java (2 of 2)
64
17.9 Trees (Cont.) Inorder traversal steps Binary tree sort
Return immediately if the reference parameter is null Traverse the left subtree with a call to inorderHelper Process the value in the node Traverse the right subtree with a call to inorderHelper Binary tree sort The inorder traversal of a binary search tree prints the node values in ascending order
65
17.9 Trees (Cont.) Preorder traversal steps
Return immediately if the reference parameter is null Process the value in the node Traverse the left subtree with a call to preorderHelper Traverse the right subtree with a call to preorderHelper
66
17.9 Trees (Cont.) Postorder traversal steps
Return immediately if the reference parameter is null Traverse the left subtree with a call to postorderHelper Traverse the right subtree with a call to postorderHelper Process the value in the node
67
17.9 Trees (Cont.) Duplicate elimination
Because duplicate values follow the same “go left” or “go right” decisions, the insertion operation eventually compares the duplicate with a same-valued node The duplicate can then be ignored Tightly packed (or balanced) trees Each level contains about twice as many elements as the previous level Finding a match or determining that no match exists among n elements requires at most log2n comparisons Level-order traversal of a binary tree Visits the nodes of the tree row by row, starting at the root node level
68
Fig. 17.19 | Binary search tree with seven values.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.