Chapter 19 - Data Structures
Chapter 19 - Data Structures
Outline
19.1 Introduction
19.2 Self-Referential Classes
19.3 Dynamic Memory Allocation
19.4 Linked Lists
19.5 Stacks
19.6 Queues
19.7 Trees
• Self-referential class
– Contains instance variable referring to object of same class
class Node {
private int data;
private Node nextNode;
// constructors and methods ...
}
• Member nextNode is a link
– nextNode “links” a Node object to another Node object
15 10
• Linked list
– Linear collection of self-referential classes (nodes)
– Connected by reference links
– Nodes can be inserted and deleted anywhere in linked list
– Last node is set to null to mark end of list
firstNode lastNode
H D ... Q
true removed
The list is: 34567 hello
hello removed
The list is: 34567
34567 removed
Empty list
(a) firstNode
7 11
new ListNode
12
(b) firstNode
7 11
new ListNode
12
12 7 11 5
12 7 11 5
12 7 11 5
(b) firstNode lastNode
12 7 11 5
removeItem
Fig 19.8 A graphical representation of the removeFromFront operation.
12 7 11 5
(b) firstNode current lastNode
12 7 11 5
removeItem
Fig 19.9 A graphical representation of the removeFromBack operation.
• Stack
– Constrained version of a linked list
• Add and remove nodes only to and from the top of the stack
– Push method adds node to top of stack
– Pop method removes node from top of stack
34567 popped
The stack is: $ true
$ popped
The stack is: true
true popped
Empty stack
com.deitel.jhtp4.ch19.EmptyListException: The stack is empty
at com.deitel.jhtp4.ch19.List.removeFromFront(List.java:92)
at com.deitel.jhtp4.ch19.StackInheritance.pop(
StackInheritance.java:22)
at StackInheritanceTest.main(StackInheritanceTest.java:38)
• Queue
– Similar to a supermarket checkout line
– Nodes inserted only at tail (back)
• Method enqueue
– Nodes removed only from head (front)
• Method dequeue
true dequeued
The queue is: $ 34567 hello
hello dequeued
Empty queue
• Tree
– Non-linear, two-dimensional data structure
• (unlike linked lists, stacks and queues)
– Nodes contain two or more links
– Root node is the first node
– Each link refers to a child
• Left child is the first node in left subtree
• Right child is the first node in right subtree
• Children of a specific node is siblings
• Nodes with no children are leaf nodes
A D
47
25 77
11 43 65 93
7 17 31 44 68
Line 34
Inserting the following values:
39 69 94 47 50 72 55 41 97 73
Preorder traversal
39 69 47 41 50 55 94 72 73 97
Inorder traversal
39 41 47 50 55 69 72 73 94 97
Postorder traversal
41 55 50 47 73 72 97 94 69 39
27
13 42
6 17 33 48