Download presentation
Presentation is loading. Please wait.
Published byCoral Wilson Modified over 9 years ago
1
1992-2007 Pearson Education, Inc. All rights reserved. 1 17 Data Structures
2
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 5 17.1 Introduction Dynamic data structures – Linear data structures Linked lists Stacks Queues – Binary trees
6
1992-2007 Pearson Education, Inc. All rights reserved. 6 17.2 Type-Wrapper Classes for Primitive Types Type-wrapper classes – In package java.lang – Enable programmers to manipulate primitive-type values as objects – Boolean, Byte, Character, Double, Float, Integer, Long and Short
7
1992-2007 Pearson Education, Inc. All rights reserved. 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 Java automatically performs these conversions (starting with Java SE 5) – Called autoboxing and auto-unboxing
8
1992-2007 Pearson Education, Inc. All rights reserved. 8 17.4 Self-Referential Classes Self-referential class – 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
1992-2007 Pearson Education, Inc. All rights reserved. 9 Fig. 17.1 | Self-referential-class objects linked together.
10
1992-2007 Pearson Education, Inc. All rights reserved. 10 17.5 Dynamic Memory Allocation 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
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 14 Insertion and deletion in a sorted array can be time consuming—all the elements following the inserted or deleted element must be shifted appropriately. Performance Tip 17.3
15
1992-2007 Pearson Education, Inc. All rights reserved. 15 17.6 Linked Lists (Cont.) Singly 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
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 17 Fig. 17.2 | Linked list graphical representation.
18
1992-2007 Pearson Education, Inc. All rights reserved. 18 Field data can refer to any object Stores a reference to the next ListNode object in the linked list
19
1992-2007 Pearson Education, Inc. All rights reserved. 19 References to the first and last ListNodes in a List Call one-argument constructor
20
1992-2007 Pearson Education, Inc. All rights reserved. 20 Initialize both references to null
21
1992-2007 Pearson Education, Inc. All rights reserved. 21
22
1992-2007 Pearson Education, Inc. All rights reserved. 22 Predicate method that determines whether the list is empty
23
1992-2007 Pearson Education, Inc. All rights reserved. 23 Display the list’s contents 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
1992-2007 Pearson Education, Inc. All rights reserved. 24
25
1992-2007 Pearson Education, Inc. All rights reserved. 25 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
1992-2007 Pearson Education, Inc. All rights reserved. 26 Deletes objects from the front of the list using method removeFromFront 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
1992-2007 Pearson Education, Inc. All rights reserved. 27
28
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 29 Fig. 17.6 | Graphical representation of operation insertAtFront.
30
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 31 Fig. 17.7 | Graphical representation of operation insertAtBack.
32
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 33 Fig. 17.8 | Graphical representation of operation removeFromFront.
34
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 35 17.6 Linked Lists (Cont.) – Assign current to lastNode – Set current.nextNode to null – Return the removedItem reference
36
1992-2007 Pearson Education, Inc. All rights reserved. 36 Fig. 17.9 | Graphical representation of operation removeFromBack.
37
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 39 Class StackInheritance extends class List Method push calls inherited method insertAtFront Method pop calls inherited method removeFromFront
40
1992-2007 Pearson Education, Inc. All rights reserved. 40 Create a StackInheritenace object Push integers onto the stack
41
1992-2007 Pearson Education, Inc. All rights reserved. 41 Pop the objects from the stack in an infinite while loop Implicitly call inherited method print Display the exception’s stack trace
42
1992-2007 Pearson Education, Inc. All rights reserved. 42
43
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 44 Outline StackComposition.java (1 of 2) private List reference push method delegates call to List method insertAtFront
45
1992-2007 Pearson Education, Inc. All rights reserved. 45 Method pop delegates call to List method removeFromFront Method isEmpty delegates call to List method isEmpty Method print delegates call to List method print
46
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 48 An object of class List Method enqueue calls List method insertAtBack
49
1992-2007 Pearson Education, Inc. All rights reserved. 49 Method dequeue calls List method removeFromFront Method isEmpty calls List method isEmpty Method print calls List method print
50
1992-2007 Pearson Education, Inc. All rights reserved. 50 Create a Queue object Enqueue four integers
51
1992-2007 Pearson Education, Inc. All rights reserved. 51 Dequeue the objects in first-in, first-out order Display the exception’s stack trace
52
1992-2007 Pearson Education, Inc. All rights reserved. 52
53
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 54 17.9 Trees (Cont.) Binary search trees – 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
1992-2007 Pearson Education, Inc. All rights reserved. 55 Fig. 17.15 | Binary tree graphical representation.
56
1992-2007 Pearson Education, Inc. All rights reserved. 56 Fig. 17.16 | Binary search tree containing 12 values.
57
1992-2007 Pearson Education, Inc. All rights reserved. 57
58
1992-2007 Pearson Education, Inc. All rights reserved. 58 Outline Tree.java (2 of 5) Allocate a new TreeNode and assign it to reference leftNode Allocate a new TreeNode and assign it to reference rightNode
59
1992-2007 Pearson Education, Inc. All rights reserved. 59 TreeNode reference to the root node of the tree Allocate a new TreeNode and assign it to reference root Call TreeNode method insert Call Tree helper method preorderHelper to begin traversal
60
1992-2007 Pearson Education, Inc. All rights reserved. 60 Call Tree helper method inorderHelper to begin traversal
61
1992-2007 Pearson Education, Inc. All rights reserved. 61 Call Tree helper method postorderHelper to begin traversal
62
1992-2007 Pearson Education, Inc. All rights reserved. 62 Create a Tree object Insert values into tree
63
1992-2007 Pearson Education, Inc. All rights reserved. 63
64
1992-2007 Pearson Education, Inc. All rights reserved. 64 17.9 Trees (Cont.) Inorder traversal steps – 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
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 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
1992-2007 Pearson Education, Inc. All rights reserved. 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 log 2 n comparisons Level-order traversal of a binary tree – Visits the nodes of the tree row by row, starting at the root node level
68
1992-2007 Pearson Education, Inc. All rights reserved. 68 Fig. 17.19 | Binary search tree with seven values.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.