PDF Graphics Java 2D 1st Edition by Asura ISBN download
PDF Graphics Java 2D 1st Edition by Asura ISBN download
com
https://ebookball.com/product/graphics-java-2d-1st-edition-
by-asura-isbn-13482/
OR CLICK HERE
DOWLOAD EBOOK
https://ebookball.com/product/graphics-java-2d-1st-edition-by-asura-
isbn-13482/
ebookball.com
ebookball.com
https://ebookball.com/product/focus-on-2d-in-direct3d-1st-edition-by-
ernest-pazera-isbn-1931841101-9781931841108-10320/
ebookball.com
Java Classes in Java Applications 1st Edition by David
Etheridge ISBN
https://ebookball.com/product/java-classes-in-java-applications-1st-
edition-by-david-etheridge-isbn-12866/
ebookball.com
ebookball.com
https://ebookball.com/product/idg-books-worldwide-1st-edition-by-
directx-3d-graphics-programming-bible-isbn-11082/
ebookball.com
https://ebookball.com/product/java-enterprise-best-practices-1st-
edition-by-o-reilly-java-isbn-0596003846-9780596003845-14366/
ebookball.com
ebookball.com
17
Data Structures
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
2 Chapter 17 Data Structures
Self-Review Exercises
17.1 Fill in the blanks in each of the following statements:
a) A self- class is used to form dynamic data structures that can grow and
shrink at execution time.
ANS: referential
b) A(n) is a constrained version of a linked list in which nodes can be inserted
and deleted only from the start of the list.
ANS: stack
c) A method that does not alter a linked list, but simply looks at it to determine whether
it is empty, is referred to as a(n) method.
ANS: predicate
d) A queue is referred to as a(n) data structure because the first nodes inserted
are the first ones removed.
ANS: first-in, first-out (FIFO)
e) The reference to the next node in a linked list is referred to as a(n) .
ANS: link
f) Automatically reclaiming dynamically allocated memory in Java is called .
ANS: garbage collection
g) A(n) is a constrained version of a linked list in which nodes can be inserted
only at the end of the list and deleted only from the start of the list.
ANS: queue
h) A(n) is a nonlinear, two-dimensional data structure that contains nodes
with two or more links.
ANS: tree
i) A stack is referred to as a(n) data structure because the last node inserted
is the first node removed.
ANS: last-in, first-out (LIFO)
j) The nodes of a(n) tree contain two link members.
ANS: binary
k) The first node of a tree is the node.
ANS: root
l) Each link in a tree node refers to a(n) or of that node.
ANS: child or subtree
m) A tree node that has no children is called a(n) node.
ANS: leaf
n) The three traversal algorithms we mentioned in the text for binary search trees are
, and .
ANS: inorder, preorder, postorder
17.2 What are the differences between a linked list and a stack?
ANS: It is possible to insert a node anywhere in a linked list and remove a node from any-
where in a linked list. Nodes in a stack may be inserted only at the top of the stack
and removed only from the top.
17.3 What are the differences between a stack and a queue?
ANS: A queue is a FIFO data structure that has references to both its head and its tail, so
that nodes may be inserted at the tail and deleted from the head. A stack is a LIFO
data structure that has a single reference to the top of the stack, where both insertion
and deletion of nodes are performed.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 3
17.4 Perhaps a more appropriate title for this chapter would have been “Reusable Data Struc-
tures.” Comment on how each of the following entities or concepts contributes to the reusability of
data structures:
a) classes
ANS: Classes allow us to instantiate as many data structure objects of a certain type (i.e.,
class) as we wish.
b) inheritance
ANS: Inheritance enables a subclass to reuse the functionality from a superclass. Public
methods of a superclass can be accessed through a subclass to eliminate duplicate log-
ic.
c) composition
ANS: Composition enables a class to reuse code by storing an instance of another class in a
field. Public methods of the member class can be called by methods in the composite
class.
17.5 Manually provide the inorder, preorder and postorder traversals of the binary search tree of
Fig. 17.20.
49
28 83
18 40 71 97
11 19 32 44 69 72 92 99
Exercises
17.6 Write a program that concatenates two linked list objects of characters. Class ListConcat-
enate should include a method concatenate that takes references to both list objects as arguments
and concatenates the second list to the first list.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
4 Chapter 17 Data Structures
9 Object data;
10 ListNode nextNode;
11
12 // constructor creates a ListNode that refers to object
13 ListNode( Object object )
14 {
15 this( object, null );
16 } // end ListNode one-argument constructor
17
18 // constructor creates ListNode that refers to
19 // Object and to next ListNode
20 ListNode( Object object, ListNode node )
21 {
22 data = object;
23 nextNode = node;
24 } // end ListNode two-argument constructor
25
26 // return reference to data in node
27 Object getObject()
28 {
29 return data; // return Object in this node
30 } // end method getObject
31
32 // return reference to next node in list
33 ListNode getNext()
34 {
35 return nextNode; // get next node
36 } // end method getNext
37 } // end class ListNode
38
39 // class List definition
40 public class List
41 {
42 private ListNode firstNode;
43 private ListNode lastNode;
44 private String name; // string like "list" used in printing
45
46 // constructor creates empty List with "list" as the name
47 public List()
48 {
49 this( "list" );
50 } // end List no-argument constructor
51
52 // constructor creates an empty List with a name
53 public List( String listName )
54 {
55 name = listName;
56 firstNode = lastNode = null;
57 } // end List one-argument constructor
58
59 // insert Object at front of List
60 public void insertAtFront( Object insertItem )
61 {
62 if ( isEmpty() ) // firstNode and lastNode refer to same object
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 5
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
6 Chapter 17 Data Structures
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 7
15 list1.insertAtFront( '5' );
16 list1.print();
17 list1.insertAtFront( '@' );
18 list1.print();
19 list1.insertAtBack( 'V' );
20 list1.print();
21 list1.insertAtBack( '+' );
22 list1.print();
23
24 // use List insert methods to add character to list2
25 System.out.println( "List 2:" );
26 list2.insertAtFront( 'P' );
27 list2.print();
28 list2.insertAtFront( 'c' );
29 list2.print();
30 list2.insertAtBack( 'M' );
31 list2.print();
32 list2.insertAtBack( '&' );
33 list2.print();
34
35 // concatenate lists using method concatenate
36 list1.concatenate( list2 );
37 System.out.println( "Concatenated list is:" );
38 list1.print();
39 } // end main
40 } // end class ListConcatenate
List 1:
The list is: 5
List 2:
The list is: P
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
8 Chapter 17 Data Structures
17.7 Write a program that merges two ordered list objects of integers into a single ordered-list
object of integers. Method merge of class ListMerge should receive references to each of the list ob-
jects to be merged and return a reference to the merged list object.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 9
50
51 // list1 element is smaller
52 if ( list1First <= list2First )
53 {
54 list2.insertAtFront( list2First ); // put item back to list2
55 return list1First;
56 } // end if
57 else
58 {
59 list1.insertAtFront( list1First ); // put item back to list1
60 return list2First;
61 } // end else
62 } // end else
63 } // end method findMin
64
65 // return merged list
66 public List getMergedList()
67 {
68 return mergedList;
69 } // end method getMergedList
70 } // end class MergeList
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
10 Chapter 17 Data Structures
17.8 Write a program that inserts 25 random integers from 0 to 100 in order into a linked-list
object. The program should calculate the sum of the elements and the floating-point average of the
elements.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 11
34 {
35 return nextNode; // get next node
36 } // end method getNext
37 } // end class ListNode
38
39 // class List definition
40 public class List
41 {
42 private ListNode firstNode;
43 private ListNode lastNode;
44 private String name; // string like "list" used in printing
45
46 // constructor creates empty List with "list" as the name
47 public List()
48 {
49 this( "list" );
50 } // end List no-argument constructor
51
52 // constructor creates an empty List with a name
53 public List( String listName )
54 {
55 name = listName;
56 firstNode = lastNode = null;
57 } // end List one-argument constructor
58
59 // insert Object at front of List
60 public void insertAtFront( Object insertItem )
61 {
62 if ( isEmpty() ) // firstNode and lastNode refer to same object
63 firstNode = lastNode = new ListNode( insertItem );
64 else // firstNode refers to new node
65 firstNode = new ListNode( insertItem, firstNode );
66 } // end method insertAtFront
67
68 // insert Object at end of List
69 public void insertAtBack( Object insertItem )
70 {
71 if ( isEmpty() ) // firstNode and lastNode refer to same Object
72 firstNode = lastNode = new ListNode( insertItem );
73 else // lastNode's nextNode refers to new node
74 lastNode = lastNode.nextNode = new ListNode( insertItem );
75 } // end method insertAtBack
76
77 // remove first node from List
78 public Object removeFromFront() throws EmptyListException
79 {
80 if ( isEmpty() ) // throw exception if List is empty
81 throw new EmptyListException( name );
82
83 Object removedItem = firstNode.data; // retrieve data being removed
84
85 // update references firstNode and lastNode
86 if ( firstNode == lastNode )
87 firstNode = lastNode = null;
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
12 Chapter 17 Data Structures
88 else
89 firstNode = firstNode.nextNode;
90
91 return removedItem; // return removed node data
92 } // end method removeFromFront
93
94 // remove last node from List
95 public Object removeFromBack() throws EmptyListException
96 {
97 if ( isEmpty() ) // throw exception if List is empty
98 throw new EmptyListException( name );
99
100 Object removedItem = lastNode.data; // retrieve data being removed
101
102 // update references firstNode and lastNode
103 if ( firstNode == lastNode )
104 firstNode = lastNode = null;
105 else // locate new last node
106 {
107 ListNode current = firstNode;
108
109 // loop while current node does not refer to lastNode
110 while ( current.nextNode != lastNode )
111 current = current.nextNode;
112
113 lastNode = current; // current is new lastNode
114 current.nextNode = null;
115 } // end else
116
117 return removedItem; // return removed node data
118 } // end method removeFromBack
119
120 // determine whether list is empty
121 public boolean isEmpty()
122 {
123 return firstNode == null; // return true if List is empty
124 } // end method isEmpty
125
126 // output List contents
127 public void print()
128 {
129 if ( isEmpty() )
130 {
131 System.out.printf( "Empty %s\n", name );
132 return;
133 } // end if
134
135 System.out.printf( "The %s is: ", name );
136 ListNode current = firstNode;
137
138 // while not at end of list, output current node's data
139 while ( current != null )
140 {
141 System.out.printf( "%s ", current.data );
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 13
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
14 Chapter 17 Data Structures
17.9 Write a program that creates a linked list object of 10 characters, then creates a second list
object containing a copy of the first list, but in reverse order.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 15
42 } // end method
43 } // end class ListReverse
List:
The list is: y c P @ 5 V + M & X
17.10 Write a program that inputs a line of text and uses a stack object to print the words of the
line in reverse order.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
16 Chapter 17 Data Structures
17.11 Write a program that uses a stack to determine whether a string is a palindrome (i.e., the
string is spelled identically backward and forward). The program should ignore spaces and punctu-
ation.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 17
50 break;
51 } // end if
52 } // end for
53
54 // display output
55 if ( flag == false )
56 System.out.println( "\nThe input string is a palindrome" );
57 else
58 System.out.println(
59 "\nThe input string is not a Palindrome" );
60 } // end try
61 catch ( EmptyListException exception )
62 {
63 System.err.printf( "\n%s", exception.toString() );
64 } // end catch
65 } // end main
66 } // end class StackTest2
17.12 Stacks are used by compilers to help in the process of evaluating expressions and generating
machine-language code. In this and the next exercise, we investigate how compilers evaluate arith-
metic expressions consisting only of constants, operators and parentheses.
Humans generally write expressions like 3 + 4 and 7 / 9 in which the operator (+ or / here) is
written between its operands—this is called infix notation. Computers “prefer” postfix notation, in
which the operator is written to the right of its two operands. The preceding infix expressions
would appear in postfix notation as 3 4 + and 7 9 /, respectively.
To evaluate a complex infix expression, a compiler would first convert the expression to post-
fix notation and evaluate the postfix version. Each of these algorithms requires only a single left-to-
right pass of the expression. Each algorithm uses a stack object in support of its operation, but each
uses the stack for a different purpose.
In this exercise, you will write a Java version of the infix-to-postfix conversion algorithm. In
the next exercise, you will write a Java version of the postfix expression evaluation algorithm. In a
later exercise, you will discover that code you write in this exercise can help you implement a com-
plete working compiler.
Write class InfixToPostfixConverter to convert an ordinary infix arithmetic expression
(assume a valid expression is entered) with single-digit integers such as
(6 + 2) * 5 - 8 / 4
to a postfix expression. The postfix version of the preceding infix expression is (note that no paren-
theses are needed)
6 2 + 5 * 8 4 / -
The program should read the expression into StringBuffer infix and use one of the stack classes
implemented in this chapter to help create the postfix expression in StringBuffer postfix. The
algorithm for creating a postfix expression is as follows:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
18 Chapter 17 Data Structures
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 19
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
20 Chapter 17 Data Structures
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 21
6 2 + 5 * 8 4 / -
The program should read a postfix expression consisting of digits and operators into a String-
Buffer. Using modified versions of the stack methods implemented earlier in this chapter, the pro-
gram should scan the expression and evaluate it (assume it is valid). The algorithm is as follows:
a) Append a right parenthesis ')' to the end of the postfix expression. When the right-
parenthesis character is encountered, no further processing is necessary.
b) When the right-parenthesis character has not been encountered, read the expression
from left to right.
If the current character is a digit, do the following:
Push its integer value on the stack (the integer value of a digit character is its
value in the computer’s character set minus the value of '0' in Unicode).
Otherwise, if the current character is an operator:
Pop the two top elements of the stack into variables x and y.
Calculate y operator x.
Push the result of the calculation onto the stack.
c) When the right parenthesis is encountered in the expression, pop the top value of the
stack. This is the result of the postfix expression.
[Note: In b) above (based on the sample expression at the beginning of this exercises), if the opera-
tor is '/', the top of the stack is 2 and the next element in the stack is 8, then pop 2 into x, pop 8
into y, evaluate 8 / 2 and push the result, 4, back on the stack. This note also applies to operator '-
'.] The arithmetic operations allowed in an expression are:
+ addition
- subtraction
* multiplication
/ division
^ exponentiation
% remainder
The stack should be maintained with one of the stack classes introduced in this chapter. You
may want to provide the following methods:
a) Method evaluatePostfixExpression, which evaluates the postfix expression.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
22 Chapter 17 Data Structures
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 23
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
24 Chapter 17 Data Structures
Empty stack
The stack is: 23
Empty stack
The stack is: 21
17.14 Modify the postfix evaluator program of Exercise 17.13 so that it can process integer oper-
ands larger than 9.
17.15 (Supermarket Simulation) Write a program that simulates a checkout line at a supermarket.
The line is a queue object. Customers (i.e., customer objects) arrive in random integer intervals of
from 1 to 4 minutes. Also, each customer is serviced in random integer intervals of from 1 to 4 min-
utes. Obviously, the rates need to be balanced. If the average arrival rate is larger than the average
service rate, the queue will grow infinitely. Even with “balanced” rates, randomness can still cause
long lines. Run the supermarket simulation for a 12-hour day (720 minutes), using the following
algorithm:
a) Choose a random integer between 1 and 4 to determine the minute at which the first
customer arrives.
b) At the first customer’s arrival time, do the following:
Determine customer’s service time (random integer from 1 to 4).
Begin servicing the customer.
Schedule arrival time of next customer (random integer 1 to 4 added to the current
time).
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 25
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
26 Chapter 17 Data Structures
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 27
90 return;
91
92 inorderHelper( node.leftNode ); // traverse left subtree
93 System.out.printf( "%d ", node.data ); // output node data
94 inorderHelper( node.rightNode ); // traverse right subtree
95 } // end method inorderHelper
96
97 // begin postorder traversal
98 public void postorderTraversal()
99 {
100 postorderHelper( root );
101 } // end method postorderTraversal
102
103 // recursive method to perform postorder traversal
104 private void postorderHelper( TreeNode node )
105 {
106 if ( node == null )
107 return;
108
109 postorderHelper( node.leftNode ); // traverse left subtree
110 postorderHelper( node.rightNode ); // traverse right subtree
111 System.out.printf( "%d ", node.data ); // output node data
112 } // end method postorderHelper
113 } // end class Tree
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
28 Chapter 17 Data Structures
29 tree.inorderTraversal();
30
31 System.out.println ( "\n\nPostorder traversal" );
32 tree.postorderTraversal();
33 System.out.println();
34 } // end main
35 } // end class TreeTest
Preorder traversal
53 31 6 3 8 8 39 97 77 69
Inorder traversal
3 6 8 8 31 39 53 69 77 97
Postorder traversal
3 8 8 6 39 31 69 77 97 53
Preorder traversal
98 7 4 66 19 51 49 64 67 66
Inorder traversal
4 7 19 49 51 64 66 66 67 98
Postorder traversal
4 49 64 51 19 66 67 66 7 98
17.17 Write a program based on the program of Figs. 17.17 and 17.18 that inputs a line of text,
tokenizes the sentence into separate words (you might want to use the StreamTokenizer class from
the java.io package), inserts the words in a binary search tree and prints the inorder, preorder and
postorder traversals of the tree.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 29
14 {
15 data = value;
16 leftNode = rightNode = null; // node has no children
17 } // end TreeNode2 one-argument constructor
18
19 // insert node
20 public void insert( String string )
21 {
22 // insert in left subtree
23 if ( string.compareTo( data ) < 0 )
24 {
25 // insert new TreeNode2
26 if ( leftNode == null )
27 leftNode = new TreeNode2( string );
28 else // continue traversing left subtree
29 leftNode.insert( string );
30 } // end if
31 else // insert in right subtree
32 {
33 // insert new TreeNode2
34 if ( rightNode == null )
35 rightNode = new TreeNode2( string );
36 else // continue traversing right subtree
37 rightNode.insert( string );
38 } // end else
39 } // end method insert
40 } // end class TreeNode2
41
42 // class Tree2 definition
43 public class Tree2
44 {
45 private TreeNode2 root;
46
47 public Tree2()
48 {
49 root = null;
50 } // end Tree2 no-argument constructor
51
52 // begin preorder traversal
53 public void preorderTraversal()
54 {
55 preorderHelper( root );
56 } // end method preorderTraversal
57
58 // recursive method to perform preorder traversal
59 private void preorderHelper( TreeNode2 node )
60 {
61 if ( node == null )
62 return;
63
64 System.out.printf( "%s ", node.data ); // output node data
65 preorderHelper( node.leftNode ); // traverse left subtree
66 preorderHelper( node.rightNode ); // traverse right subtree
67 } // end method preorderHelper
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
30 Chapter 17 Data Structures
68
69 // begin inorder traversal
70 public void inorderTraversal()
71 {
72 inorderHelper( root );
73 } // end method inorderTraversal
74
75 // recursive method to perform inorder traversal
76 private void inorderHelper( TreeNode2 node )
77 {
78 if ( node == null )
79 return;
80
81 inorderHelper( node.leftNode ); // traverse left subtree
82 System.out.printf( "%s ", node.data ); // output node data
83 inorderHelper( node.rightNode ); // traverse right subtree
84 } // end method inorderHelper
85
86 // begin postorder traversal
87 public void postorderTraversal()
88 {
89 postorderHelper( root );
90 } // end method postorderTraversal
91
92 // recursive method to perform postorder traversal
93 private void postorderHelper( TreeNode2 node )
94 {
95 if ( node == null )
96 return;
97
98 postorderHelper( node.leftNode ); // traverse left subtree
99 postorderHelper( node.rightNode ); // traverse right subtree
100 System.out.printf( "%s ", node.data ); // output node data
101 } // end method postorderHelper
102
103 public void insertNode( String string )
104 {
105 // tree is empty
106 if ( root == null )
107 root = new TreeNode2( string );
108 else // call TreeNode2 method insert on root
109 root.insert( string );
110 } // end method insertNode
111 } // end class Tree2
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 31
9 {
10 public static void main( String args[] )
11 {
12 // get input string
13 Scanner scanner = new Scanner( System.in );
14 System.out.println( "Please enter a string:" );
15 String input = scanner.nextLine();
16 StringTokenizer tokens = new StringTokenizer( input );
17 Tree2 tree = new Tree2();
18
19 // insert input string into tree
20 while ( tokens.hasMoreTokens() )
21 tree.insertNode( tokens.nextToken() );
22
23 System.out.println( "\n\nPreorder traversal" );
24 tree.preorderTraversal();
25
26 System.out.println( "\n\nInorder traversal" );
27 tree.inorderTraversal();
28
29 System.out.println( "\n\nPostorder traversal" );
30 tree.postorderTraversal();
31 } // end main
32 } // end class Tree2Test
Preorder traversal
I have been a inserted into tree
Inorder traversal
I a been have inserted into tree
Postorder traversal
a been tree into inserted have I
17.18 In this chapter, we saw that duplicate elimination is straightforward when creating a binary
search tree. Describe how you would perform duplicate elimination when using only a one-dimen-
sional array. Compare the performance of array-based duplicate elimination with the performance
of binary-search-tree-based duplicate elimination.
17.19 Write a method depth that receives a binary tree and determines how many levels it has.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
32 Chapter 17 Data Structures
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 33
62
63 // begin preorder traversal
64 public void preorderTraversal()
65 {
66 preorderHelper( root );
67 } // end method preorderTraversal
68
69 // recursive method to perform preorder traversal
70 private void preorderHelper( TreeNode node )
71 {
72 if ( node == null )
73 return;
74
75 System.out.printf( "%d ", node.data ); // output node data
76 preorderHelper( node.leftNode ); // traverse left subtree
77 preorderHelper( node.rightNode ); // traverse right subtree
78 } // end method preorderHelper
79
80 // begin inorder traversal
81 public void inorderTraversal()
82 {
83 inorderHelper( root );
84 } // end method inorderTraversal
85
86 // recursive method to perform inorder traversal
87 private void inorderHelper( TreeNode node )
88 {
89 if ( node == null )
90 return;
91
92 inorderHelper( node.leftNode ); // traverse left subtree
93 System.out.printf( "%d ", node.data ); // output node data
94 inorderHelper( node.rightNode ); // traverse right subtree
95 } // end method inorderHelper
96
97 // begin postorder traversal
98 public void postorderTraversal()
99 {
100 postorderHelper( root );
101 } // end method postorderTraversal
102
103 // recursive method to perform postorder traversal
104 private void postorderHelper( TreeNode node )
105 {
106 if ( node == null )
107 return;
108
109 postorderHelper( node.leftNode ); // traverse left subtree
110 postorderHelper( node.rightNode ); // traverse right subtree
111 System.out.printf( "%d ", node.data ); // output node data
112 } // end method postorderHelper
113
114 // recursively determine the depth
115 public int depth()
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
34 Chapter 17 Data Structures
116 {
117 return calculateLevel( root );
118 } // end method depth
119
120 // recursively determine the depth
121 private int calculateLevel( TreeNode node )
122 {
123 // if node is a leaf
124 if ( node.rightNode == null && node.leftNode == null )
125 return 0;
126 else
127 {
128 // search each of the subtrees
129 int left = 0;
130 int right = 0;
131
132 if ( node.leftNode != null )
133 left = calculateLevel( node.leftNode );
134
135 if ( node.rightNode != null )
136 right = calculateLevel( node.rightNode );
137
138 // pass on the depth of the deeper subtree
139 if ( left > right )
140 return left + 1;
141 else
142 return right + 1;
143 } // end else
144 } // end method calculateLevel
145 } // end class Tree
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 35
Preorder traversal
50 35 32 5 45 81 65 71 82 85
Inorder traversal
5 32 35 45 50 65 71 81 82 85
Postorder traversal
5 32 45 35 71 65 85 82 81 50
17.20 (Recursively Print a List Backward) Write a method printListBackward that recursively out-
puts the items in a linked list object in reverse order. Write a test program that creates a sorted list
of integers and prints the list in reverse order.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
36 Chapter 17 Data Structures
21 {
22 data = object;
23 nextNode = node;
24 } // end ListNode two-argument constructor
25
26 // return reference to data in node
27 Object getObject()
28 {
29 return data; // return Object in this node
30 } // end method getObject
31
32 // return reference to next node in list
33 ListNode getNext()
34 {
35 return nextNode; // get next node
36 } // end method getNext
37 } // end class ListNode
38
39 // class List definition
40 public class List
41 {
42 private ListNode firstNode;
43 private ListNode lastNode;
44 private String name; // string like "list" used in printing
45
46 // constructor creates empty List with "list" as the name
47 public List()
48 {
49 this( "list" );
50 } // end List no-argument constructor
51
52 // constructor creates an empty List with a name
53 public List( String listName )
54 {
55 name = listName;
56 firstNode = lastNode = null;
57 } // end List one-argument constructor
58
59 // insert Object at front of List
60 public void insertAtFront( Object insertItem )
61 {
62 if ( isEmpty() ) // firstNode and lastNode refer to same object
63 firstNode = lastNode = new ListNode( insertItem );
64 else // firstNode refers to new node
65 firstNode = new ListNode( insertItem, firstNode );
66 } // end method insertAtFront
67
68 // insert Object at end of List
69 public void insertAtBack( Object insertItem )
70 {
71 if ( isEmpty() ) // firstNode and lastNode refer to same Object
72 firstNode = lastNode = new ListNode( insertItem );
73 else // lastNode's nextNode refers to new node
74 lastNode = lastNode.nextNode = new ListNode( insertItem );
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 37
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
38 Chapter 17 Data Structures
129 if ( isEmpty() )
130 {
131 System.out.printf( "Empty %s\n", name );
132 return;
133 } // end if
134
135 System.out.printf( "The %s is: ", name );
136 ListNode current = firstNode;
137
138 // while not at end of list, output current node's data
139 while ( current != null )
140 {
141 System.out.printf( "%s ", current.data );
142 current = current.nextNode;
143 } // end while
144
145 System.out.println( "\n" );
146 } // end method print
147
148 // print list backwards
149 public void printListBackwards()
150 {
151 System.out.print( "Reverse ordered list: " );
152 reverse( firstNode );
153 System.out.println();
154 } // end method printListBackwards
155
156 // reverse node
157 private void reverse( ListNode currentNode )
158 {
159 if ( currentNode == null )
160 return;
161 else
162 reverse( currentNode.getNext() );
163
164 System.out.printf( "%s ", currentNode.data );
165 } // end method reverse
166 } // end class List
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 39
17.21 (Recursively Search a List) Write a method searchList that recursively searches a linked list
object for a specified value. Method searchList should return a reference to the value if it is found;
otherwise, null should be returned. Use your method in a test program that creates a list of integers.
The program should prompt the user for a value to locate in the list.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
40 Chapter 17 Data Structures
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 41
84
85 // update references firstNode and lastNode
86 if ( firstNode == lastNode )
87 firstNode = lastNode = null;
88 else
89 firstNode = firstNode.nextNode;
90
91 return removedItem; // return removed node data
92 } // end method removeFromFront
93
94 // remove last node from List
95 public Object removeFromBack() throws EmptyListException
96 {
97 if ( isEmpty() ) // throw exception if List is empty
98 throw new EmptyListException( name );
99
100 Object removedItem = lastNode.data; // retrieve data being removed
101
102 // update references firstNode and lastNode
103 if ( firstNode == lastNode )
104 firstNode = lastNode = null;
105 else // locate new last node
106 {
107 ListNode current = firstNode;
108
109 // loop while current node does not refer to lastNode
110 while ( current.nextNode != lastNode )
111 current = current.nextNode;
112
113 lastNode = current; // current is new lastNode
114 current.nextNode = null;
115 } // end else
116
117 return removedItem; // return removed node data
118 } // end method removeFromBack
119
120 // determine whether list is empty
121 public boolean isEmpty()
122 {
123 return firstNode == null; // return true if List is empty
124 } // end method isEmpty
125
126 // output List contents
127 public void print()
128 {
129 if ( isEmpty() )
130 {
131 System.out.printf( "Empty %s\n", name );
132 return;
133 } // end if
134
135 System.out.printf( "The %s is: ", name );
136 ListNode current = firstNode;
137
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
42 Chapter 17 Data Structures
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 43
26 if ( searchResult != null )
27 System.out.println( "Value found: 34" );
28 else
29 System.out.println( "Value not found: 34" );
30
31 searchResult = list.search( 50 );
32
33 // display result of searching 50
34 if ( searchResult != null )
35 System.out.println( "Value found: 50" );
36 else
37 System.out.println( "Value not found: 50" );
38
39 searchResult = list.search( 72 );
40
41 // display result of searching 72
42 if ( searchResult != null )
43 System.out.println( "Value found: 72" );
44 else
45 System.out.println( "Value not found: 72" );
46 } // end main
47 } // end class ListTest
17.22 (Binary Tree Delete) In this exercise, we discuss deleting items from binary search trees. The
deletion algorithm is not as straightforward as the insertion algorithm. Three cases are encountered
when deleting an item—the item is contained in a leaf node (i.e., it has no children), the item is
contained in a node that has one child or the item is contained in a node that has two children.
If the item to be deleted is contained in a leaf node, the node is deleted and the reference in
the parent node is set to null.
If the item to be deleted is contained in a node with one child, the reference in the parent
node is set to reference the child node and the node containing the data item is deleted. This causes
the child node to take the place of the deleted node in the tree.
The last case is the most difficult. When a node with two children is deleted, another node in
the tree must take its place. However, the reference in the parent node cannot simply be assigned to
reference one of the children of the node to be deleted. In most cases, the resulting binary search
tree would not embody the following characteristic of binary search trees (with no duplicate val-
ues): The values in any left subtree are less than the value in the parent node, and the values in any right
subtree are greater than the value in the parent node.
Which node is used as a replacement node to maintain this characteristic? It is either the node
containing the largest value in the tree less than the value in the node being deleted, or the node
containing the smallest value in the tree greater than the value in the node being deleted. Let us
consider the node with the smaller value. In a binary search tree, the largest value less than a par-
ent’s value is located in the left subtree of the parent node and is guaranteed to be contained in the
rightmost node of the subtree. This node is located by walking down the left subtree to the right
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
44 Chapter 17 Data Structures
until the reference to the right child of the current node is null. We are now referencing the
replacement node, which is either a leaf node or a node with one child to its left. If the replacement
node is a leaf node, the steps to perform the deletion are as follows:
a) Store the reference to the node to be deleted in a temporary reference variable.
b) Set the reference in the parent of the node being deleted to reference the replacement
node.
c) Set the reference in the parent of the replacement node to null.
d) Set the reference to the right subtree in the replacement node to reference the right sub-
tree of the node to be deleted.
e) Set the reference to the left subtree in the replacement node to reference the left subtree
of the node to be deleted.
The deletion steps for a replacement node with a left child are similar to those for a replace-
ment node with no children, but the algorithm also must move the child into the replacement
node’s position in the tree. If the replacement node is a node with a left child, the steps to perform
the deletion are as follows:
a) Store the reference to the node to be deleted in a temporary reference variable.
b) Set the reference in the parent of the node being deleted to reference the replacement
node.
c) Set the reference in the parent of the replacement node to reference the left child of the
replacement node.
d) Set the reference to the right subtree in the replacement node to reference the right sub-
tree of the node to be deleted.
e) Set the reference to the left subtree in the replacement node to reference the left subtree
of the node to be deleted.
Write method deleteNode, which takes as its argument the value to delete. Method delete-
Node should locate in the tree the node containing the value to delete and use the algorithms dis-
cussed here to delete the node. If the value is not found in the tree, the method should print a
message that indicates whether the value is deleted. Modify the program of Figs. 17.17 and 17.18
to use this method. After deleting an item, call the methods inorderTraversal, preorderTra-
versal and postorderTraversal to confirm that the delete operation was performed correctly.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 45
20 // locate insertion point and insert new node; ignore duplicate values
21 public void insert( int insertValue )
22 {
23 // insert in left subtree
24 if ( insertValue < data )
25 {
26 // insert new TreeNode
27 if ( leftNode == null )
28 leftNode = new TreeNode( insertValue );
29 else // continue traversing left subtree
30 leftNode.insert( insertValue );
31 } // end if
32 else // insert in right subtree
33 {
34 // insert new TreeNode
35 if ( rightNode == null )
36 rightNode = new TreeNode( insertValue );
37 else // continue traversing right subtree
38 rightNode.insert( insertValue );
39 } // end else if
40 } // end method insert
41 } // end class TreeNode
42
43 // class Tree5 declaration
44 public class Tree5
45 {
46 protected TreeNode root;
47
48 public Tree5()
49 {
50 root = null;
51 } // end Tree5 no-argument constructor
52
53 // Insert new node in the binary tree. If the root is null, create the
54 // root here. Otherwise, call the insert method of class TreeNode.
55 public void insertNode( int d )
56 {
57 if ( root == null )
58 root = new TreeNode( d );
59 else
60 root.insert( d );
61 } // end method insertNode
62
63 // Preorder Traversal
64 public void preorderTraversal()
65 {
66 preorderHelper( root );
67 } // end method preorderTraversal
68
69 // Recursive method to perform preorder traversal
70 private void preorderHelper( TreeNode node )
71 {
72 if ( node == null )
73 return;
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
46 Chapter 17 Data Structures
74
75 System.out.printf( "%d ", node.data );
76 preorderHelper( node.leftNode );
77 preorderHelper( node.rightNode );
78 } // end method preorderHelper
79
80 // Inorder Traversal
81 public void inorderTraversal()
82 {
83 inorderHelper( root );
84 } // end method inorderTraversal
85
86 // Recursive method to perform inorder traversal
87 private void inorderHelper( TreeNode node )
88 {
89 if ( node == null )
90 return;
91
92 inorderHelper( node.leftNode );
93 System.out.printf( "%d ", node.data );
94 inorderHelper( node.rightNode );
95 } // end method inorderHelper
96
97 // Postorder Traversal
98 public void postorderTraversal()
99 {
100 postorderHelper( root );
101 } // end method postorderTraversal
102
103 // Recursive method to perform postorder traversal
104 private void postorderHelper( TreeNode node )
105 {
106 if ( node == null )
107 return;
108
109 postorderHelper( node.leftNode );
110 postorderHelper( node.rightNode );
111 System.out.printf( "%d ", node.data );
112 } // end method postorderHelper
113
114 // top level method call
115 public void deleteItem( int d )
116 {
117 // if the tree is empty
118 if ( root == null )
119 return;
120
121 int test = root.data;
122
123 // if the root is the value to be deleted
124 if ( test == d )
125 {
126 // if the left child is null, set root to the right
127 if ( root.leftNode == null )
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 47
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
48 Chapter 17 Data Structures
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 49
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
50 Chapter 17 Data Structures
Preorder traversal
96 57 55 35 2 3 23 13 33 45 37 91 59 57 87 70 69 77 80 93
Inorder traversal
2 3 13 23 33 35 37 45 55 57 57 59 69 70 77 80 87 91 93 96
Postorder traversal
13 33 23 3 2 37 45 35 55 57 69 80 77 70 87 59 93 91 57 96
Deleted value: 80
Preorder traversal
96 57 55 35 2 3 23 13 33 45 37 91 59 57 87 70 69 77 93
Inorder traversal
2 3 13 23 33 35 37 45 55 57 57 59 69 70 77 87 91 93 96
Postorder traversal
13 33 23 3 2 37 45 35 55 57 69 77 70 87 59 93 91 57 96
17.23 (Binary Tree Search) Write method binaryTreeSearch, which attempts to locate a specified
value in a binary-search-tree object. The method should take as an argument a search key to be lo-
cated. If the node containing the search key is found, the method should return a reference to that
node; otherwise, it should return a null reference.
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Another Random Document on
Scribd Without Any Related Topics
Puolipäivän rinnassa herttua ratsasti linnaan neuvos- ja
hoviherrojen seuraamana. Hän oli puettu punaiseen samettipukuun,
joka oli reunustettu kärppäturkiksin samoin kuin hattukin, jota
ympäröi avopäällyksinen herttuallinen kruunu puhtaasta kullasta.
Hevonen oli lumivalkoinen, suitset, satula ja hihnat välkkyivät
kullasta ja jalokivistä.
Anna Vaasa saattoi olla ihastuttava, kun niin tahtoi, ja nyt hän
pani kaiken kykynsä liikkeelle. Kustaa Brahe tunsi yhä suurempaa
vetoa tähän tenhopiiriin. Mutta samalla kalvoi häntä
mustasukkaisuus, ja tuhannet kerrat hän kyseli itseltään,
heittäytyisikö prinsessan jalkoihin kysyen, tahtoiko tämä vielä kuulua
hänelle ja tunnustaa syntinsä…
*****
"Mitähän se on?"
"Ei ole ritarillista puhua minulle tällaista, kun minun täytyisi pysyä
tyynenä eikä näyttää tietäväni mistään", vastasi Anna nuhdellen.
"Minä siunaan tätä hetkeä, suloinen Anna; sano, että rakastat
minua!"
"No?"
Hän kertoi tälle kaiken, sillä olihan äiti sen ilmankin arvannut.
Eikä Kristina rouva hidastellut ilmoittaa asiaa miehelleen.
Suutarin naama loisti ilosta, kun hän kuuli mistä oli kysymys. Hän
lupasi hyvää tavaraa huokeaan hintaan.
"Pankaamme tasan!"
"Maltas sinä", huusi heistä toinen ja tarttui naiseen. Mutta tämä oli
yhtä väkevä kuin urhokaskin ja antoi iskun iskusta.
"Anna Banér."
"Valtaneuvoksen tytär?"
"Niin."
"Sellainen tyttö!"
*****
"Millä tavoin?"
"Sinä, rakas isä! Ei, ei, tyttäresi voi itsekin kostaa puolestaan."
"Millä tavoin?"
"Ei, kautta taivaan!" vastasi Kustaa herra hymyillen. "Ja totta on,
ettei häntä voisi pahemmin nolata. Mutta pelkään, ettei äitisi tule
kuunaan suostumaan."
"Häpeämätön!"
"Ensi viikolla."
"Hyvä, siihen mennessä harjoittelemme." Niin he tekivätkin.
KATOLINEN HALLITUS.
*****
"Miksi niin?"
"Mutta rajakreivi…"
ebookball.com