2001 prentice hall, inc. all rights reserved. chapter 20 – data structures outline...
TRANSCRIPT
2001 Prentice Hall, Inc. All rights reserved.
Chapter 20 – Data Structures
Outline20.1 Introduction20.2 Self-referential Structures20.3 Linked Lists20.4 Doubly Linked Lists20.5 Stacks and Queues20.6 Trees20.7 Hashes
2001 Prentice Hall, Inc. All rights reserved.
20.1 Introduction
• Dynamic Data Structures– Grow and shrink at runtime– Linked lists
• Allow easy insertion and deletion– Stacks
• Allow only insertion and removal from the top– Queues
• Represent waiting lines– Binary trees
• High speed searching and sorting of data
2001 Prentice Hall, Inc. All rights reserved.
20.2 Self-referential Structures
• Self-referential structure– Contains members that refer to members of the same type
• Nodes– Contain data– Also contain references to another node
• Links
2001 Prentice Hall, Inc. All rights reserved.
20.3 Linked Lists
• Linked list– Linear collection of nodes– Accessed through the first node of the list– The last node of a list has a reference of undef– Used when the number of elements is unknown– Removing data from the middle does not require a shift
• It simply changes the references of the nodes
2001 Prentice Hall, Inc. All rights reserved.
20.3 Linked Lists
1015
Fig. 20.1 Two self-referential class objects linked together.
2001 Prentice Hall, Inc. All rights reserved.
20.3 Linked Lists
H D Q...
$linkedList
Fig. 20.2 Graphical representation of a linked list.
2001 Prentice Hall, Inc. All rights reserved.
Outline
30 $linkedList = $second;29 # aim head reference at new first element2827 $second->{ nextLink } = $first;26 $first->{ nextLink } = $second->{ nextLink };
25 my ($first, $second) = ($linkedList, $linkedList->{nextLink});24 # swap first two elements2322 traverseList( $linkedList ); # output current list contents21 "the list contains:\n" );20 print( "\nAfter adding four elements to the list, ",1918 $linkedList = { data => "cleaning", nextLink => $linkedList };17 $linkedList = { data => "groceries", nextLink => $linkedList };16 $linkedList = { data => "batteries", nextLink => $linkedList };15 # add more elements to $linkedList1413 $linkedList = { data => "haircut", nextLink => $linkedList };12 # add an element to $linkedList1110 traverseList( $linkedList ); # output current list contents98 my $linkedList = undef; # defines head reference76 use strict;5 use warnings;43 # A simple demonstration of linked lists.2 # Figure 20.3: fig20_03.pl1 #!/usr/bin/perl
fig20_03.plThis is the linked list, it is undefined because there are no nodes in it
Inserts a new item at the front of the list
Adds a new object and connects it to the head of the list which is haircut
Swaps two elements in the list
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_03.pl
6160 $current = $current->{ nextLink }; # move to next node59 print( "$current->{ data }" ); # print current data58 while ( defined( $current ) ) { 5756 }55 return;54 print( "The list is empty.\n" );53 if ( !defined( $current ) ) {5251 my $current = shift();50 {49 sub traverseList 48 # receives as an argument.47 # Function to output the contents of the linked list it 4645 traverseList( $linkedList ); # output current list contents44 "the list contains:\n" );43 print( "\nAfter deleting the third element, ", 4241 $third = undef;40 $second->{ nextLink } = $third->{ nextLink };39 my $third = $linkedList->{ nextLink }->{ nextLink };3837 $second = $linkedList->{ nextLink };36 # delete third element3534 traverseList( $linkedList ); # output current list contents33 "the list contains:\n" );32 print( "\nAfter swapping the first two elements, ",31
Removes the third element from the list
Checks to make sure that the list is not empty
Outputs the contents of the list until the end of the list is reached
Sets the link of the second to be equal to the link of the third
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_03.pl
Program OutputThe list is empty. After adding four elements to the list,the list contains:cleaning --> groceries --> batteries --> haircut After swapping the first two elements,the list contains:groceries --> cleaning --> batteries --> haircut After deleting the third element,the list contains:groceries --> cleaning --> haircut
62 if ( defined( $current ) ) { # if next node exists,
63 print( " --> " ); # output -->
64 }
65 }
66
67 print( "\n" );
68 }
2001 Prentice Hall, Inc. All rights reserved.
20.3 Linked Lists
a)
b)
$linkedList
$linkedList
haircut
batteries
new node
new node
haircut
batteries
Fig. 20.4 Inserting a new node in a list.
2001 Prentice Hall, Inc. All rights reserved.
20.3 Linked Lists
$linkedList
batteries
cleaning
groceries
haircut
$second
$third
a)
$linkedList
batteries
cleaning
groceries
haircut
$second
$third
b)
Fig. 20.5 Removing a node from a list.
2001 Prentice Hall, Inc. All rights reserved.
Outline
LinkedList.pm
18 }
25 my $type = shift();
31 }30 return $self;29 bless( $self, $class );28 27 my $self = { head => undef };26 my $class = ref( $type ) || $type;
24 {23 sub new 22 # LinkedList constructor 2120 package LinkedList; # start package LinkedList 19
17 return $self;16 bless( $self, $class );15 14 my $self = { data => $_[ 0 ], nextLink => $_[ 1 ] };13 my $class = ref( $type ) || $type;12 my $type = shift();11 {10 sub new 9 # ListNode constructor 87 package ListNode; # start package ListNode 65 use strict;4 use warnings;32 # Object-oriented linked-list implementation.1 # Fig. 20.6: LinkedList.pm
The constructor for the ListNode object
Creates the data and nextLink members of the new node
The constructor for the LinkedList
Sets its value to undef, meaning it is an empty list
2001 Prentice Hall, Inc. All rights reserved.
Outline
LinkedList.pm
60
59 }
58 }
57 $previous->{nextLink} = new ListNode( $data, $current );
56 else {
55 }
54 $self->{ head } = new ListNode( $data, $current );
53 unless ( defined( $previous ) ) {
52 # at the head of the list.
51 # if $previous is still undefined, we are inserting
50
49 }
48 $current = $current->{ nextLink };
47 $previous = $current;
46 while( defined( $current ) && $data gt $current->{ data }) {
45 # being inserted.
44 # inserted and $current references the node after the one
43 # $previous references the node before the one being
42 # node will be inserted. When this loop completes, variable
41 # This loop determines the nodes between which the new
40
39 my $current = $self->head();
38 my $previous = undef;
37
36 my ( $self, $data ) = @_;
35 {
34 sub insertNode
33 # function to insert a new node in the list in ascending order
32
Will insert a new node in the determined location
Loops until the correct previous and next node are found
If the previous node is undefined then the new node is the first node
2001 Prentice Hall, Inc. All rights reserved.
Outline
LinkedList.pm
90 }89 return 1; # element was deleted8887 }86 $previous->{ nextLink } = $current->{ nextLink };85 else {84 }83 $self->{ head } = $self->{ head }{ nextLink };82 unless ( defined( $previous ) ) { 8180 if ( defined( $current ) ) { 79 # we delete it and return 1 78 # if we found the element in the list,77 76 }75 $current = $current->{ nextLink };74 $previous = $current;
73 while ( defined( $current ) && $data ne $current->{ data } ) {72 # being deleted.71 # the one being deleted and $current references the node 70 # completes, variable $previous references the node before 69 # This loop locates the node to delete. When this loop 68 67 my $current = $self->head();66 my $previous = undef;65 64 my ( $self, $data ) = @_;63 {62 sub deleteNode 61 # function to remove a node from the list
Will delete a node
Finds the right node to be deleted and gets the nodes before and after it
Makes sure the value to be deleted is in the list, and if so, returns 1 to confirm the delete
2001 Prentice Hall, Inc. All rights reserved.
Outline
LinkedList.pm
122 }121 }120 print( " --> " ); # output -->119 if ( defined( $current ) ) { # if next node exists,118 117 $current = $current->{ nextLink }; # move to next node116 print( $current->{ data } ); # print current data115 while ( defined( $current ) ) {114113 my $current = $self->{ head };112 print( "The list is:\n" );111110 } 109 return;108 print( "List is empty.\n\n" );107 if ( !defined( $self->head() ) ) {106 105 my $self = shift();104{103sub printList 102# function that traverses the list and outputs each element101100}99 return $_[ 0 ]->{ head };98 { 97 sub head 96 # function that returns the head reference for the list9594 }93 }92 return 0; # element was not deleted91 else {
Returns the first reference in the list
Makes sure the list is not empty
Prints the data of the current node and then moves to the next node
2001 Prentice Hall, Inc. All rights reserved.
Outline
LinkedList.pm
127 return 1;
126
125}
124 print( "\n" );
123
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_06.pl
153
152} while ( $choice ne 'q' );
151 print( "\n" );
150
149 instructions() if ( $choice eq '?' );
148
147 deleteIt() if ( $choice eq 'd' );
146
145 insertIt() if ( $choice eq 'i' );
144
143 chomp( $choice = <STDIN> );
142 print( "? " );
141do {
140
138
137my $choice;
136my $ll = new LinkedList();
135
134use LinkedList;
133use strict;
132use warnings;
131
130# Using class LinkedList.
129# Fig. 20.6: fig20_06.pl
128#!/usr/bin/perl
139instructions();
Creates a new LinkedList object
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_06.pl
183}182DONE181 ? to print instructions.180 q to end. 179 d to delete an element from the list.178 i to insert an element into the list.177Enter your choice:176 print << 'DONE';175{174sub instructions 173# displays the instructions172171}170 $ll->printList();169 "$item not found.\n" ); 168 print( $ll->deleteNode( $item )? "$item deleted.\n" : 167 chomp( my $item = <STDIN> );166 print( "Enter string to be deleted: " );165{164sub deleteIt163# deletes a node from the list and outputs the list162161}160 $ll->printList();159 $ll->insertNode( $item );158 chomp( my $item = <STDIN> );157 print( "Enter a string: " );156{155sub insertIt154# inserts a node in the list and outputs the list
Prompts the user for an item to insert and then inserts it into the list
Prompts the user for an item to be deleted and then removes it from the list
Prints out the current list
2001 Prentice Hall, Inc. All rights reserved.
OutlineEnter your choice: i to insert an element into the list. d to delete an element from the list. q to end. ? to print instructions.? iEnter a string: CThe list is:C ? iEnter a string: AThe list is:A --> C ? iEnter a string: EThe list is:A --> C --> E ? dEnter string to be deleted: EE deleted.The list is:A --> C ? dEnter string to be deleted: AA deleted.The list is:C
fig20_06.plProgram Output
continued…
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_06.plProgram Output
? dEnter string to be deleted: CC deleted.List is empty. ? q
2001 Prentice Hall, Inc. All rights reserved.
20.4 Doubly Linked Lists
• Doubly linked lists– Each node knows which node comes after it– Each node knows which node comes before it– Insertion and deletion is similar to that of a linked list
2001 Prentice Hall, Inc. All rights reserved.
Outline
3029 my $self = { };28 my $class = ref( $type ) || $type;27 my $type = shift();26 {25 sub new 24 # DoublyLinkedList constructor2322 package DoublyLinkedList;2120 }19 return $self;18 bless( $self, $class );17 16 data => $_[ 2 ] };15 nextLink => $_[ 1 ],14 my $self = { previousLink => $_[ 0 ],13 my $class = ref( $type ) || $type;12 my $type = shift();11 {10 sub new 9 # DoublyLinkedListNode constructor87 package DoublyLinkedListNode;65 use strict;4 use warnings;32 # Implementation of a doubly linked list.1 # Figure 20.7: DoublyLinkedList.pm
DoublyLinkedList.pm
Creates a new node object
Has a reference to the node before and after it
2001 Prentice Hall, Inc. All rights reserved.
Outline
58
57 }
56 $self->{ cursor }->{ previousLink } = $newnode;
55 $self->{ cursor }->{ previousLink }->{ nextLink } = $newnode;
54
53 $self->{ cursor }, $data );
52 $self->{ cursor }->{ previousLink },
51 my $newnode = new DoublyLinkedListNode(
50
49 }
48 return;
47 if ( !defined( $data ) ) {
46
45 my ( $self, $data ) = @_;
44 {
43 sub insertNode
42 # sets the cursor to that element.
41 # inserts an element before the cursor and
40
39 }
38 return $self;
37 bless( $self, $class );
36
35 $self->{ cursor } = $self->{ head }{ nextLink };
34 new DoublyLinkedListNode( $self->{ head } );
33 $self->{ head }{ nextLink } =
32 $self->{ head } = new DoublyLinkedListNode();
31 # head and tail dummy nodes
DoublyLinkedList.pmCreates the head of the new DoublyLinkedList
Checks to see if data was entered
Sets the previous link and the next link of the new node
2001 Prentice Hall, Inc. All rights reserved.
Outline
90 }89 return $self->{ cursor }{ data };88 $self->{ cursor } = $self->{ cursor }{ nextLink };87 defined( $self->{ cursor }{ nextLink }{ data } ) ) {86 if ( defined( $self->{ cursor }->{ nextLink } ) &&8584 my $self = shift();83 {82 sub nextNode 81 # moves the cursor to the next node in the list8079 }78 return $deleted;77 76 $self->{ cursor } = $self->{ cursor }->{ nextLink };75 my $deleted = $self->{ cursor }->{ data };7473 $self->{ cursor }->{ previousLink };72 $self->{ cursor }->{ nextLink }->{ previousLink } = 71 $self->{ cursor }->{ nextLink };70 $self->{ cursor }->{ previousLink }->{ nextLink } = 69 68 }67 return undef;66 print "You don't have an element selected\n";65 if ( !defined( $self->{ cursor }->{ data } ) ) {64 63 my ( $self ) = shift();62 {61 sub deleteNode60 # node's data ( or undefined if no node is selected ).59 # deletes the current cursor element and returns the deleted
DoublyLinkedList.pm
Sets the previous node to the next node and the next node to the previous node to complete the double link
Moves the cursor to the next node in the list
2001 Prentice Hall, Inc. All rights reserved.
Outline
102 unless( defined( $self->{ cursor }{ previousLink } ) &&
119
118}
117 return $_[ 0 ]->{ cursor }->{ data };
116 $_[ 0 ]->{ cursor } = $_[ 0 ]->{ head }{ nextLink };
115{
114sub gotoHead
113# moves the cursor to the head of the list
112
111}
110 return $self->{ cursor }->{ data };
109 $self->{ cursor } = $self->{ cursor }->{ previousLink };
108
107 }
106 return;
105 print( "Can not go to the previous node.\n" );
104
103 defined( $self->{ cursor }{ previousLink }{ data } ) ) {
101
100 my $self = shift();
99 {
98 sub previousNode
97 # moves the cursor to the previous node in the list
96
95 }
94 }
93 return undef;
92 print( "Can not go to the next node.\n" );
91 else {
DoublyLinkedList.pm
Moves the cursor to the previous node in the list
Moves the cursor to the head of the list making the next node the first
2001 Prentice Hall, Inc. All rights reserved.
Outline
DoublyLinkedList.pm
134 return;
144 print( "TAIL\n" );
147return 1;147 return 1; 146
145}
143
142 }
141 $current = $current->{ nextLink };
140 print( "$current->{ data } <--> " );
139 while ( defined( $current->{ data } ) ) {
138
137 print( "HEAD <--> " );
136
135 }
133 print( "The list is empty.\n\n" );
132 if ( !defined( $current->{ data } ) ) {
131
130 my $current = $self->{ head }{ nextLink };
129 my $self = shift();
128{
127sub printAll
126# prints the list contents
125
124}
123 return $_[ 0 ]->{ cursor }->{ data };
122{
121sub data
120# returns the data at the current cursor location
Displays the data that the cursor is at
Makes sure the list is not empty
Loops through to print out all the items in the list
2001 Prentice Hall, Inc. All rights reserved.
Outline
165
179$dll->previousNode();178print( "Attempting to go before the first list element:\n" );177176print( "Now at ", $dll->previousNode(), ".\n" );175print( "Now at ", $dll->previousNode(), ".\n" );174print( "\nNow at ", $dll->data(), ".\n" );173172$dll->printAll(); # display list contents171 "The list contains:\n" );170print( "\nAfter deleting two elements, ",169$dll->deleteNode(); # delete node at current position168$dll->nextNode(); # move to next node167$dll->deleteNode(); # delete node at current position
164print( "\nThe head is ", $dll->gotoHead(), ".\n" );163$dll->printAll(); # display list contents162print( "The list contains:\n" );161160}159 $dll->insertNode( $_ );158for ( 1 .. 5 ) {157156my $dll = new DoublyLinkedList();155154use DoublyLinkedList;153use strict;152use warnings;151150# Using a doubly-linked list.149# Figure 20.7: fig20_07.pl148#!/usr/bin/perl
166$dll->nextNode(); # move to next node
fig20_07.pl
Creates a list with the numbers 1 through 5
Moves to and deletes the next node on the list
Moves backwards through the list
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_07.plProgram Output
The list contains:HEAD <--> 1 <--> 2 <--> 3 <--> 4 <--> 5 <--> TAIL The head is 1. After deleting two elements, The list contains:HEAD <--> 1 <--> 3 <--> 5 <--> TAIL Now at 5.Now at 3.Now at 1.Attempting to go before the first list element:Can not go to the previous node.
2001 Prentice Hall, Inc. All rights reserved.
20.5 Stacks and Queues
• Stacks– Like a linked list with a few restraints
• Nodes can only be added to the top• Nodes can only be removed from the top
– LIFO (Last In First Out)– Last node is set to undef– The push function is used to add nodes– The pop function is used to remove nodes
2001 Prentice Hall, Inc. All rights reserved.
20.5 Stacks and Queues
• Queue– Like a linked list with a few restraints
• Nodes can only be added to the tail• Nodes can only be removed from the head
– FIFO (First In First Out)– The enqueue operation is used to add nodes– The dequeue operation is used to remove nodes
2001 Prentice Hall, Inc. All rights reserved.
Outline
29
28 print( "Pop remaining elements: " );
27
26 }
25 push( @stack, $_ );
24 for ( 21 .. 25 ) {
23
22 print( "\nPush 21 to 25\n" );
21
20 }
19 print( pop( @stack ), " " );
18 for ( 1 .. 10 ) {
17
16 print( "Pop the top 10 elements: " );
15
14 }
13 push( @stack, $_ );
12 for ( 1 .. 20 ) {
11
10 print( "Using the stack:\nPush 1 to 20\n" );
9
8 my ( @stack, @queue );
7
6 use strict;
5 use warnings;
4
3 # Demonstrating stacks and queues.
2 # Figure 20.8: fig20_08.pl
1 #!/usr/bin/perl
fig20_08.pl
Creates an array for a stack and an array for a queue
Pushes 1 through 20 onto the array stack
Pops the first 10 elements on that stack
Pushes 5 more elements onto the stack, they will come before the original elements
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_08.pl
56 }
55 print( shift( @queue ), " " );
54 while ( @queue ) {
53
52 print( "Dequeue remaining elements: " );
51
50 }
49 push( @queue, $_ );
48 for ( 21 .. 25 ) {
47
46 print( "\nEnqueue 21 to 25...\n" );
45
44 }
43 print( shift( @queue ), " " );
42 for ( 1 .. 10 ) {
41
40 print( "Dequeue first 10 elements: " );
39
38 }
37 push( @queue, $_ );
36 for ( 1 .. 20 ) {
35
34 print( "\n\nUsing the queue:\nEnqueue 1 to 20\n" );
33
32 }
31 print( pop( @stack ), " " );
30 while ( @stack ) {
Enqueue 20 elements
shift is it used to remove the first elements and then shift the rest down to the proper locations
Adds 5 more elements to the list, they will be added to the back
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_08.plProgram Output
Using the stack:Push 1 to 20Pop the top 10 elements: 20 19 18 17 16 15 14 13 12 11Push 21 to 25Pop remaining elements: 25 24 23 22 21 10 9 8 7 6 5 4 3 2 1 Using the queue:Enqueue 1 to 20Dequeue first 10 elements: 1 2 3 4 5 6 7 8 9 10Enqueue 21 to 25...Dequeue remaining elements: 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
2001 Prentice Hall, Inc. All rights reserved.
20.6 Trees
• Trees– Trees are non linear, two dimensional data structures– Binary trees
• Each node contains two links– Two, one, or none of those links may be undef
– The root node is the first node– Each link the root has is a child– The left child is the first node in the left subtree– The right child is the first node in the right subtree– Children of nodes are called siblings– A node without children is called a leaf– Trees are drawn from the root down, the opposite of a real
tree
2001 Prentice Hall, Inc. All rights reserved.
20.6 Trees (II)
• Binary search trees– Has no duplicate values– Left subtree values are less than the parent– Right subtree values are greater than the parent– The order the values are inserted changes the look of the tree
2001 Prentice Hall, Inc. All rights reserved.
20.6 Trees (III)
• Traversals– In order traversal
• Value of the left child• Value of the node• Value of the right child
– Pre order traversal• Value of the node• Value of the left child • Value of the right child
– Post order traversal• Value of the left child• Value of the right child• Value of the node
2001 Prentice Hall, Inc. All rights reserved.
20.6 Trees
right childD
C
B
A
root node
left child
Fig. 20.9 Graphical representation of a binary tree.
2001 Prentice Hall, Inc. All rights reserved.
20.6 Trees
Fig. 20.10 Binary search tree.
47
25
11
7 17
43
31 44
77
65 93
68
2001 Prentice Hall, Inc. All rights reserved.
Outline
BinarySearchTree.pm
19 return $self;
31 }30 $self->{ left }->insert( $data );29 if ( defined( $self->{ left } ) ) {28 if ( $data < $self->{ data } ) {2726 my ( $self, $data ) = @_;25 {24 sub insert 23 # ignore duplicate values22 # insert a TreeNode in a tree that contains nodes;2120 }
18 bless( $self, $class );1716 { left => undef, data => shift(), right => undef };15 my $self = 14 $class = ref( $type ) || $type;13 my $type = shift();12 {11 sub new 10 # TreeNode constructor98 my $class;7 package TreeNode;65 use strict;4 use warnings;32 # Implementation of a binary search tree.1 # Fig. 20.11: BinarySearchTree.pm
Creates a new tree node
Each node knows its children but does not know who its parent is
If the left tree is not empty then a recursive call is made
If the data is less than the parent is it sent to the left tree
2001 Prentice Hall, Inc. All rights reserved.
Outline
BinarySearchTree.pm
59
58 }
57 if ( defined( $self->{ right } ) );
56 $self->{ right }->preOrder()
55
54 if ( defined( $self->{ left } ) );
53 $self->{ left }->preOrder()
52
51 print( "$self->{ data } " );
50
49 my $self = shift();
48 {
47 sub preOrder
46 # performs a preorder traversal of a binary search tree
45
44 }
43 }
42 }
41 $self->{ right } = new TreeNode( $data );
40 else {
39 }
38 $self->{ right }->insert( $data );
37 if ( defined( $self->{ right } ) ) {
36 elsif ( $data > $self->{ data } ) {
35 }
34 }
33 $self->{ left } = new TreeNode( $data );
32 else {
The recursion continues until an undefined node is reached, and then a new node is made
If the right child is defined a recursive call is made
If the data is greater than the node, it is sent to the right tree
Prints the data of the node
Recursive call to left child
Recursive call to right child
2001 Prentice Hall, Inc. All rights reserved.
Outline
BinarySearchTree.pm
87
86 }
85 print( "$self->{ data } " );
84
83 if ( defined( $self->{ right } ) );
82 $self->{ right }->postOrder()
81
80 if ( defined( $self->{ left } ) );
79 $self->{ left }->postOrder()
78
77 my $self = shift();
76 {
75 sub postOrder
74 # performs a postorder traversal of a binary search tree
73
72 }
71 if ( defined( $self->{ right } ) );
70 $self->{ right }->inOrder()
69
68 print( "$self->{ data } " );
67
66 if ( defined( $self->{ left } ) );
65 $self->{ left }->inOrder()
64
63 my $self = shift();
62 {
61 sub inOrder
60 # performs an inorder traversal of a binary search tree
A recursive call to the left child
Prints out the data of the node
A recursive call to the right child
A recursive call to the left child
Prints out the data of the node
A recursive call to the right child
2001 Prentice Hall, Inc. All rights reserved.
Outline
BinarySearchTree.pm
88 # recursively outputs the binary tree in a tree format turned89 # on its side with the root node at the left of the output, the90 # rightmost child at the top of the output and the leftmost 91 # child at the bottom of the output92 sub outputTree 93 {
95
97 $self->{ right }->outputTree( $depth + 3 );98 }99
101102 if ( defined( $self->{ left } ) ) {
104 }105}106107package BinarySearchTree;108109# BinarySearchTree constructor
111{
114
119118}117 return $self;116 bless( $self, $class );115 my $self = { root => undef };
96 if ( defined( $self->{ right } ) ) {
103 $self->{ left }->outputTree( $depth + 3 );
100 print( ' ' x $depth, "$self->{ data }\n" );
94 my ( $self, $depth ) = @_;
113 my $class = ref( $type ) || $type;112 my $type = shift();
110sub new Creates a new binary search tree object
2001 Prentice Hall, Inc. All rights reserved.
Outline
BinarySearchTree.pm
120# inserts a node in a binary search tree
121sub insertNode
122{
123 my ( $self, $data ) = @_;
124
125 unless ( defined( $self->{ root } ) ) {
126 $self->{ root } = new TreeNode( $data );
127 }
128 else {
129 $self->{ root }->insert( $data );
130 }
131}
132
133# begins the preorder traversal
134sub printPreOrder
135{
136 my ( $self, $node ) = @_;
137 $self->{ root }->preOrder();
138}
139
140# begins the inorder traversal
141sub printInOrder
142{
143 my ( $self, $node ) = @_;
144 $self->{ root }->inOrder();
145}
146
Inserts a new tree node into the binary search tree
Creates the root if needed
Prints the tree using an in-order traversal
Prints the tree using pre-order traversal
2001 Prentice Hall, Inc. All rights reserved.
Outline
BinarySearchTree.pm
161 return 1; 160
159}
158 $self->{ root }->outputTree( 0 );
157 my ( $self ) = shift();
156{
155sub printTree
154# begin output of tree in tree format
153
152}
151 $self->{ root }->postOrder();
150 my ( $self ) = shift();
149{
148sub printPostOrder
147# begins the postorder traversal
Prints the tree in a post-order traversal
Displays all the nodes in a tree fashion
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_11.pl
190$tree->printPostOrder();
189print( "\n\nThe postOrder traversal is: \n" );
188
187$tree->printInOrder();
186print( "\n\nThe inOrder traversal is: \n" );
185
184$tree->printPreOrder();
183print( "\nThe preOrder traversal is: \n" );
182
181$tree->printTree();
180print( "\n\nThe tree looks like:\n" );
179
178}
177 $tree->insertNode( $data );
176 print( "$data " );
175 my $data = int( rand( 15 ) );
174for ( 1 .. 15 ) {
173
172print( "The numbers being placed in the tree are:\n" );
171
170my $tree = new BinarySearchTree();
169
168use BinarySearchTree;
167use strict;
166use warnings;
165
164# Using a binary search tree.
163# Fig. 20.11: fig20_11.pl
162#/usr/bin/perl
Creates a new binary tree object
Places 15 random numbers into the tree, no repeats
Displays the tree
Displays the trees using the 3 types of traversals
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_11.plProgram Output
The numbers being placed in the tree are: 9 7 12 10 9 13 2 2 8 13 8 12 3 3 14 The tree looks like: 14 13 12 109 8 7 3 2 The preOrder traversal is:9 7 2 3 8 12 10 13 14 The inOrder traversal is:2 3 7 8 9 10 12 13 14 The postOrder traversal is:3 2 8 7 10 14 13 12 9
2001 Prentice Hall, Inc. All rights reserved.
20.7 Hashes
• Hashtable– Non linear data structure– Contain multiple containers called buckets– Hash function is used to determine which bucket a value
should be placed in• Must map equal values to the same bucket• Good functions distribute evenly
2001 Prentice Hall, Inc. All rights reserved.
Outline
Hashtable.pm
27
26 }
25 return $self;
24 bless( $self, $class );
23
22 }
21 $self->{ table }->[ $_ ] = [ ];
20 foreach ( 0 .. $self->{ size } - 1 ) {
19
18 shift() || hashFunction( $self->{ size } );
17 $self->{ function } =
16 $self->{ size } = shift() || 23; # 23 is default size
15 my $self = { table => [ ]};
14
13 my $class = ref( $type ) || $type;
12 my $type = shift();
11 {
10 sub new
9 # Hashtable constructor
8
7 package Hashtable;
6
5 use strict;
4 use warnings;
3
2 # Simple hash table implementation.
1 # Fig. 20.12: Hashtable.pm
Sets the size of the hashtable, 23 if not specified
Uses array elements as buckets
2001 Prentice Hall, Inc. All rights reserved.
Outline
Hashtable.pm
5756 }55 return 0;54 53 }52 }51 return 1;50 $_, 1, @{ [] } );49 splice( @{ $self->{ table }[ $index ] }, 48 print "Deleting $data\n";47 if ( $self->{ table }[ $index ][ $_ ] eq $data ) {46 foreach ( 0 .. $#{ $self->{ table }[ $index ] } ) {4544 my $index = $self->{ function }->( $data );43 42 my $data = shift();41 my $self = shift();40 sub remove {39 # removes an element from the table3837 }36 return $index;35 push( @{ $self->{ table }[ $index ] }, $data );34 my $index = $self->{ function }->( $data );33 32 my $data = shift();31 my $self = shift();30 {29 sub insert 28 # inserts an element in the table
Inserts an element by calling the hash function and putting the data in appropriately
Uses the function to find the right bucket and then searches the bucket for the data
2001 Prentice Hall, Inc. All rights reserved.
Outline
Hashtable.pm
86 return 1;
85
84 }
83 }
82 return $number % $size;
81
80 }
79 $number += ord( substr( $string, 0, 1, '' ) );
78 while ( $string ) {
77
76 my $number;
75 my $string = shift();
74 {
73 return sub
72
71 my $size = shift();
70 {
69 sub hashFunction
68 # calculates the location of a key in the table
67
66 }
65 }
64 print "Bucket $i: @{ $self->{ table }[ $i ] }\n";
63 for ( my $i = 0; $i < $self->{ size }; $i++ ) {
62
61 my $self = shift();
60 {
59 sub printTable
58 # outputs the contents of the table
The hash function
Returns the ASCII total and divides by the number of buckets, returning the remainder
Displays the hash table
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_12.pl
116 }115 print( "\n" );114113 }112 chomp( $data = <STDIN> );111 $ht->insert($data), "\n" );110 print( "Inserted '$data' into slot ", 109 while ( $data ne 'DONE' ) {108107 chomp( my $data = <STDIN> );106 "('DONE' to terminate input):\n" );105 print( "Enter several strings on separate lines\n",104 if ( $choice eq 'i' ) {103 102while ( $choice ne 'q' ) {101100chomp( $choice = <STDIN> );99 print( "? " );98 instructions();9796 my $choice = '';95 my $ht = new Hashtable( 11 );9493 use Hashtable;92 use strict;91 use warnings;9089 # Simple hash table implementation.88 # Fig. 20.12: fig20_12.pl87 #!/usr/bin/perl
Creates a new Hashtable with 11 buckets
A loop that accepts several inputs at a time
Each input is inserted into the table
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_12.pl
143
142}
141 chomp( $choice = <STDIN> );
140 print( "? " );
139
138 }
137 "Enter '?' for instructions.\n\n" );
136 print( "Please enter a valid command. ",
135 else {
134 }
133 instructions();
132 elsif ( $choice eq '?' ) {
131 }
130 print( "\n" );
129 $ht->printTable();
128 elsif ( $choice eq 'd' ) {
127 }
126 }
125 print( "\n" );
124 else {
123 }
122 print( "Could not delete $data\n\n" );
121 unless ( $ht->remove( $data ) ) {
120
119 chomp( my $data = <STDIN> );
118 print( "What element would you like to remove? " );
117 elsif ( $choice eq 'r' ) {
Removes one element from the hashtable
Prints the table
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_12.pl
Program OutputEnter 'i' to insert numbers.Enter 'r' to remove numbers.Enter 'd' to display hash table.Enter '?' to print these instructions.Enter 'q' to quit.? iEnter several strings on separate lines('DONE' to terminate input):helloInserted 'hello' into slot 4thereInserted 'there' into slot 8
154}
153DONE
152Enter 'q' to quit.
151Enter '?' to print these instructions.
150Enter 'd' to display hash table.
149Enter 'r' to remove numbers.
148Enter 'i' to insert numbers.
147
146print <<DONE
145{
144sub instructions
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_12.plProgram Output
happyInserted 'happy' into slot 7birthdayInserted 'birthday' into slot 8toInserted 'to' into slot 7youInserted 'you' into slot 8newInserted 'new' into slot 0yearInserted 'year' into slot 4DONE ? dBucket 0: newBucket 1:Bucket 2:Bucket 3:Bucket 4: hello yearBucket 5:Bucket 6:Bucket 7: happy toBucket 8: there birthday youBucket 9:Bucket 10: ? rWhat element would you like to remove? birthdayDeleting birthday
2001 Prentice Hall, Inc. All rights reserved.
Outline
fig20_12.plProgram Output
? dBucket 0: newBucket 1:Bucket 2:Bucket 3:Bucket 4: hello yearBucket 5:Bucket 6:Bucket 7: happy toBucket 8: there youBucket 9:Bucket 10: ? q