100% found this document useful (34 votes)
65 views

PDF Graphics Java 2D 1st Edition by Asura ISBN download

The document promotes the ebook collection available at ebookball.com, featuring various titles related to graphics programming and data structures in Java. It includes links to specific books such as 'Graphics Java 2D' and 'Introduction to Computer Graphics Using Java 2D and 3D'. Additionally, it contains educational content on data structures, including linked lists, stacks, and queues, along with self-review exercises and programming examples.

Uploaded by

doumalpobbul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (34 votes)
65 views

PDF Graphics Java 2D 1st Edition by Asura ISBN download

The document promotes the ebook collection available at ebookball.com, featuring various titles related to graphics programming and data structures in Java. It includes links to specific books such as 'Graphics Java 2D' and 'Introduction to Computer Graphics Using Java 2D and 3D'. Additionally, it contains educational content on data structures, including linked lists, stacks, and queues, along with self-review exercises and programming examples.

Uploaded by

doumalpobbul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

Explore the full ebook collection and download it now at ebookball.

com

Graphics Java 2D 1st Edition by Asura ISBN

https://ebookball.com/product/graphics-java-2d-1st-edition-
by-asura-isbn-13482/

OR CLICK HERE

DOWLOAD EBOOK

Browse and Get More Ebook Downloads Instantly at https://ebookball.com


Click here to visit ebookball.com and download ebookball now
Your digital treasures (PDF, ePub, MOBI) await
Download instantly and pick your perfect format...

Read anywhere, anytime, on any device!

Graphics Java 2D 1st Edition by Asura ISBN

https://ebookball.com/product/graphics-java-2d-1st-edition-by-asura-
isbn-13482/

ebookball.com

Introduction to Computer Graphics Using Java 2D and 3D


Undergraduate Topics in Computer Science 1st Edition by
Frank Klawonn ISBN 1447127323 9781447127321
https://ebookball.com/product/introduction-to-computer-graphics-using-
java-2d-and-3d-undergraduate-topics-in-computer-science-1st-edition-
by-frank-klawonn-isbn-1447127323-9781447127321-19850/

ebookball.com

Progresses in the Analysis of Stochastic 2D Cellular


Automata A Study of Asynchronous 2D Minority 1st Edition
by Damien Regnault, Nicolas Schabanel, Eric Thierry ISBN
9783540744566
https://ebookball.com/product/progresses-in-the-analysis-of-
stochastic-2d-cellular-automata-a-study-of-
asynchronous-2d-minority-1st-edition-by-damien-regnault-nicolas-
schabanel-eric-thierry-isbn-9783540744566-11508/
ebookball.com

Focus On 2D in Direct3D 1st Edition by Ernest Pazera ISBN


1931841101 9781931841108

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

Delphi Graphics and Game Programming Exposed with DirectX


For versions 5 0 7 0 Table of Contents 1st Edition by
Delphi Graphics
https://ebookball.com/product/delphi-graphics-and-game-programming-
exposed-with-directx-for-versions-5-0-7-0-table-of-contents-1st-
edition-by-delphi-graphics-11194/

ebookball.com

IDG Books WorldWide 1st Edition by DirectX 3D Graphics


Programming Bible ISBN

https://ebookball.com/product/idg-books-worldwide-1st-edition-by-
directx-3d-graphics-programming-bible-isbn-11082/

ebookball.com

Java Enterprise Best Practices 1st Edition by O Reilly


Java ISBN 0596003846 9780596003845

https://ebookball.com/product/java-enterprise-best-practices-1st-
edition-by-o-reilly-java-isbn-0596003846-9780596003845-14366/

ebookball.com

Java Java Java Object Oriented Problem Solving 3rd Edition


by Ralph Morelli, Ralph Walde ISBN 0131474340
9780131474345
https://ebookball.com/product/java-java-java-object-oriented-problem-
solving-3rd-edition-by-ralph-morelli-ralph-walde-
isbn-0131474340-9780131474345-12410/

ebookball.com
17
Data Structures

Much that I bound, I could


not free;
Much that I freed returned
to me.
—Lee Wilson Dodd
OBJECTIVES
‘Will you walk a little
faster?’ said a whiting to a In this chapter you will learn:
snail, ■ To form linked data structures using references, self-
‘There’s a porpoise close referential classes and recursion.
behind us, and he’s treading
on my tail.’ ■ The type-wrapper classes that enable programs to
—Lewis Carroll process primitive data values as objects.
■ To use autoboxing to convert a primitive value to an
There is always room at the
object of the corresponding type-wrapper class.
top.
—Daniel Webster ■ To use auto-unboxing to convert an object of a type-
wrapper class to a primitive value.
Push on—keep moving.
■ To create and manipulate dynamic data structures, such
—Thomas Morton as linked lists, queues, stacks and binary trees.

I’ll turn over a new leaf.


■ Various important applications of linked data structures.
—Miguel de Cervantes ■ How to create reusable data structures with classes,
inheritance and composition.

© 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

Fig. 17.20 | Binary search tree with 15 nodes.

ANS: The inorder traversal is


11 18 19 28 32 40 44 49 69 71 72 83 92 97 99
The preorder traversal is
49 28 18 11 19 40 32 44 83 71 69 72 97 92 99
The postorder traversal is
11 19 18 32 44 40 28 69 72 71 92 99 97 83 49

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:

1 // Exercise 17.6 Solution: List.java


2 // ListNode and List class definitions.
3 package com.deitel.jhtp7.ch17;
4
5 // class to represent one node in a list
6 class ListNode
7 {
8 // package access members; List can access these directly

© 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

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;
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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
6 Chapter 17 Data Structures

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 );
142 current = current.nextNode;
143 } // end while
144
145 System.out.println( "\n" );
146 } // end method print
147
148 // concatenates two lists and stores the results in the first list
149 public void concatenate( List two )
150 {
151 while ( !two.isEmpty() )
152 insertAtBack( two.removeFromFront() );
153 } // end method concatenate
154 } // end class List

1 // Exercise 17.6 Solution: ListConcatenate.java


2 // Program concatenates two lists
3 import com.deitel.jhtp7.ch17.List;
4
5 public class ListConcatenate
6 {
7 public static void main( String args[] )
8 {
9 // create two linked lists
10 List list1 = new List();
11 List list2 = new List();
12
13 // use List insert methods to add characters to list1
14 System.out.println( "List 1:" );

© 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

The list is: @ 5

The list is: @ 5 V

The list is: @ 5 V +

List 2:
The list is: P

The list is: c P

The list is: c P M

The list is: c P M &

Concatenated list is:


The list is: @ 5 V + c P M &

© 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:

1 // Exercise 17.7 Solution: MergeList.java


2 // Program merges two ordered integer list.
3 package com.deitel.jhtp7.ch17;
4
5 public class MergeList extends List
6 {
7 List list1; // list1 and list2 are two
8 List list2; // lists to be merged
9 List mergedList; // merged list of list1 and list2
10
11 // constructor merges two lists
12 public MergeList( List first, List second )
13 {
14 list1 = first;
15 list2 = second;
16 mergedList = new List();
17 merge();
18 } // end three-argument MergeList constructor
19
20 // merge two ordered list
21 private void merge()
22 {
23 // get min of two list element
24 Integer smallElement = findMin();
25
26 // insert into return list
27 while ( smallElement != null )
28 {
29 mergedList.insertAtBack( smallElement );
30 smallElement = findMin();
31 } // end while
32 } // end method merge
33
34 // find min of two list
35 private Integer findMin()
36 {
37 int list1First, list2First;
38
39 // list1 and list2 both are empty
40 if ( list1.isEmpty() && list2.isEmpty() )
41 return null;
42 else if ( list1.isEmpty() ) // list1 is empty
43 return ( Integer ) list2.removeFromFront();
44 else if ( list2.isEmpty() ) // list2 is empty
45 return ( Integer ) list1.removeFromFront();
46 else // neither list1 nor list2 is empty
47 {
48 list1First = ( Integer ) list1.removeFromFront();
49 list2First = ( Integer ) list2.removeFromFront();

© 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

1 // Exercise 17.7 Solution: MergeListTest.java


2 // Program inserts sorted numbers in two lists and merges them
3 import com.deitel.jhtp7.ch17.MergeList;
4 import com.deitel.jhtp7.ch17.List;
5
6 public class MergeListTest
7 {
8 public static void main( String args[] )
9 {
10 List list1 = new List();
11 List list2 = new List();
12 int[] first = { 3, 12, 15, 19, 24, 38, 50, 61, 70, 99 };
13 int[] second = { 5, 7, 10, 25, 33, 67, 78, 100 };
14
15 // add list1 elements to fist
16 for ( int intValue : first )
17 list1.insertAtBack( intValue );
18
19 // add list2 elements to second
20 for ( int intValue : second )
21 list2.insertAtBack( intValue );
22
23 System.out.println( "First list is: " );
24 list1.print();
25
26 System.out.println( "Second list is: " );
27 list2.print();
28
29 // merge two list and display merged list
30 MergeList mergeList = new MergeList( list1, list2 );
31 List mergedList = mergeList.getMergedList();

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
10 Chapter 17 Data Structures

32 System.out.println( "Merged list is: " );


33 mergedList.print();
34 } // end main
35 } // end class MergeListTest

First list is:


The list is: 3 12 15 19 24 38 50 61 70 99

Second list is:


The list is: 5 7 10 25 33 67 78 100

Merged list is:


The list is: 3 5 7 10 12 15 19 24 25 33 38 50 61 67 70 78 99 100

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:

1 // Exercise 17.8 Solution: List.java


2 // ListNode and List class definitions.
3 package com.deitel.jhtp7.ch17;
4
5 // class to represent one node in a list
6 class ListNode
7 {
8 // package access members; List can access these directly
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()

© 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

142 current = current.nextNode;


143 } // end while
144
145 System.out.println( "\n" );
146 } // end method print
147
148 // calculates and returns sum of every value in list
149 public int sum()
150 {
151 int sum = 0;
152 ListNode current = firstNode;
153
154 // cycle through list adding values to total
155 while ( current != null )
156 {
157 sum += ( Integer ) current.getObject();
158 current = current.getNext();
159 } // end while
160
161 return sum;
162 } // end method add
163 } // end class List

1 // Exercise 17.8 Solution: ListTest.java


2 // Program inserts random numbers in a list,
3 // prints the sum, and displays the average.
4 import java.util.Random;
5 import com.deitel.jhtp7.ch17.List;
6
7 public class ListTest
8 {
9 public static void main( String args[] )
10 {
11 List list = new List();
12 int newNumber;
13 Random randomNumber = new Random();
14
15 // create Integers to store in list
16 for ( int k = 1; k <= 25; k++ )
17 {
18 newNumber = randomNumber.nextInt( 101 );
19 list.insertAtFront( newNumber );
20 } // end for
21
22 list.print();
23
24 int sum = list.sum();
25 System.out.printf(
26 "Sum is: %d\nAverage: %.3f", sum, sum / 25.0f );
27 } // end main
28 } // end class ListTest

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
14 Chapter 17 Data Structures

The list is: 36 39 53 94 19 86 52 47 96 75 84 53 78 19 20 2 41 100 10 23 78


21 68 33 77

Sum is: 1304


Average: 52.160

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:

1 // Exercise 17.9 Solution: ListReverse.java


2 // Program creates a list, then creates a reverse of the list
3 import com.deitel.jhtp7.ch17.List;
4
5 public class ListReverse
6 {
7 public static void main( String args[] )
8 {
9 // create two linked lists
10 List list1 = new List();
11 List list2 = new List();
12
13 // use List insert methods
14 list1.insertAtFront( '5' );
15 list1.insertAtFront( '@' );
16 list1.insertAtBack( 'V' );
17 list1.insertAtBack( '+' );
18 list1.insertAtFront( 'P' );
19 list1.insertAtFront( 'c' );
20 list1.insertAtBack( 'M' );
21 list1.insertAtBack( '&' );
22 list1.insertAtFront( 'y' );
23 list1.insertAtBack( 'X' );
24
25 System.out.println( "List: " );
26 list1.print();
27
28 list2 = reverse( list1 ); // reverse lists
29 System.out.println( "Reversed list is:" );
30 list2.print();
31 } // end main
32
33 // reverses a list and returns it to the caller
34 public static List reverse( List one )
35 {
36 List reversed = new List();
37
38 while ( !one.isEmpty() )
39 reversed.insertAtFront( one.removeFromFront() );
40
41 return reversed;

© 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

Reversed list is:


The list is: X & M + V 5 @ P c y

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:

1 // Exercise 17.10 Solution: StackTest.java


2 // Program prints the words of a line in reverse
3 import java.util.Scanner;
4 import java.util.StringTokenizer;
5 import com.deitel.jhtp7.ch17.StackComposition;
6
7 public class StackTest
8 {
9 public static void main( String args[] )
10 {
11 StackComposition stack = new StackComposition();
12
13 // get input text
14 Scanner scanner = new Scanner( System.in );
15 System.out.println( "Please enter a string" );
16 String input = scanner.nextLine();
17 StringTokenizer tokenizer = new StringTokenizer( input );
18
19 // take each word from tokenizer and push on stack
20 while ( tokenizer.hasMoreTokens() )
21 stack.push( tokenizer.nextToken() );
22
23 System.out.println( "\nInput string in reverse order:" );
24
25 // build reverse string by popping words from stack.
26 while ( !stack.isEmpty() )
27 {
28 Object removedObject = stack.pop();
29 System.out.printf( "%s ", removedObject );
30 } // end while
31 } // end main
32 } // end class StackTest

Please enter a string


print this string in reverse

Input string in reverse order:


reverse in string this print

© 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:

1 // Exercise 17.11 Solution: StackTest2.java


2 // Program tests for a palindrome.
3 import java.util.Scanner;
4 import com.deitel.jhtp7.ch17.StackComposition;
5 import com.deitel.jhtp7.ch17.EmptyListException;
6
7 public class StackTest2
8 {
9 public static void main( String args[] )
10 {
11 StackComposition stack = new StackComposition();
12
13 // get input string
14 Scanner scanner = new Scanner( System.in );
15 System.out.println( "Please enter a string:" );
16 String input = scanner.nextLine();
17
18 char letter; // character in string
19 Object removedObject = null; // object removed from stack
20 boolean flag = false; // true if string is palindrome
21
22 // cycle through input one char at a time to
23 // create stack of all relevant characters
24 for ( int i = 0; i < input.length(); i++ )
25 {
26 letter = input.charAt( i );
27
28 if ( Character.isLetterOrDigit( letter ) )
29 stack.push( letter );
30 } // end for
31
32 // test for palindrome
33 try
34 {
35 for ( int count = 0;
36 count < input.length() && !stack.isEmpty(); count++ )
37 {
38 letter = input.charAt( count );
39
40 // ignore spaces and punctuation
41 if ( !Character.isLetterOrDigit( letter ) )
42 continue;
43
44 removedObject = stack.pop();
45
46 // not palindrome
47 if ( letter != ( ( Character ) removedObject ) )
48 {
49 flag = true;

© 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

Please enter a string:


madam i'm adam

The input string is a palindrome

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

a) Push a left parenthesis '(' on the stack.


b) Append a right parenthesis ')' to the end of infix.
c) While the stack is not empty, read infix from left to right and do the following:
If the current character in infix is a digit, append it to postfix.
If the current character in infix is a left parenthesis, push it onto the stack.
If the current character in infix is an operator:
Pop operators (if there are any) at the top of the stack while they have equal
or higher precedence than the current operator, and append the popped
operators to postfix.
Push the current character in infix onto the stack.
If the current character in infix is a right parenthesis:
Pop operators from the top of the stack and append them to postfix until
a left parenthesis is at the top of the stack.
Pop (and discard) the left parenthesis from the stack.
The following arithmetic operations are allowed in an expression:
+ addition
- subtraction
* multiplication
/ division
^ exponentiation
% remainder
The stack should be maintained with stack nodes that each contain an instance variable and a
reference to the next stack node. Some of the methods you may want to provide are as follows:
a) Method convertToPostfix, which converts the infix expression to postfix notation.
b) Method isOperator, which determines whether c is an operator.
c) Method precedence, which determines whether the precedence of operator1 (from the
infix expression) is less than, equal to or greater than the precedence of operator2 (from
the stack). The method returns true if operator1 has lower precedence than operator2.
Otherwise, false is returned.
d) Method stackTop (this should be added to the stack class), which returns the top value
of the stack without popping the stack.
ANS:

1 // Exercise 17.12 Solution:InfixToPostfixConverter.java


2 // Infix to postfix conversion
3 import com.deitel.jhtp7.ch17.EmptyListException;
4 import com.deitel.jhtp7.ch17.StackComposition;
5
6 public class InfixToPostfixConverter
7 {
8 // take out the infix and change it into postfix
9 public static StringBuffer convertToPostfix( StringBuffer infix )
10 {
11 CharacterStack charStack = new CharacterStack();
12 StringBuffer temporary = new StringBuffer( "" );
13
14 // push a left paren onto the stack and add a right paren to infix
15 charStack.pushChar( '(' );
16 infix.append( ')' );
17
18 // convert the infix expression to postfix

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 19

19 for ( int infixCount = 0; !charStack.isEmpty(); ++infixCount )


20 {
21 if ( Character.isDigit( infix.charAt( infixCount ) ) )
22 temporary.append( infix.charAt( infixCount ) + " " );
23 else if ( infix.charAt( infixCount ) == '(' )
24 charStack.pushChar( '(' );
25 else if ( isOperator( infix.charAt( infixCount ) ) )
26 {
27 while ( isOperator( charStack.stackTop() ) &&
28 precedence( charStack.stackTop(),
29 infix.charAt( infixCount ) ) )
30 temporary.append( charStack.popChar() + " " );
31
32 charStack.pushChar( infix.charAt( infixCount ) );
33 } // end else if
34 else if ( infix.charAt( infixCount ) == ')' )
35 {
36 while ( charStack.stackTop() != '(' )
37 temporary.append( charStack.popChar() + " " );
38
39 charStack.popChar();
40 } // end else if
41 } // end for
42
43 return temporary;
44 } // end method convertToPostfix
45
46 // check if c is an operator
47 private static boolean isOperator( char c )
48 {
49 if ( c == '+' || c == '-' || c == '*' || c == '/' || c == '^' )
50 return true;
51 else
52 return false;
53 } // end method isOperator
54
55 // ensure proper order of operations
56 private static boolean precedence( char operator1, char operator2 )
57 {
58 if ( operator1 == '^' )
59 return true;
60 else if ( operator2 == '^' )
61 return false;
62 else if ( operator1 == '*' || operator1 == '/' )
63 return true;
64 else if ( operator1 == '+' || operator1 == '-' )
65 {
66 if ( operator2 == '*' || operator2 == '/' )
67 return false;
68 else
69 return true;
70 } // end else if
71
72 return false;

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
20 Chapter 17 Data Structures

73 } // end method precedence


74 } // end class InfixToPostfixConverter
75
76 class CharacterStack extends StackComposition
77 {
78 public char stackTop()
79 {
80 char temp = popChar();
81 pushChar( temp );
82
83 return temp;
84 } // end method stackTop
85
86 public char popChar()
87 {
88 return ( ( Character )super.pop() );
89 } // end method popChar
90
91 public void pushChar( char c )
92 {
93 super.push( c );
94 } // end method pushChar
95 } // end class CharacterStack

1 // Exercise 17.12 Solution:InfixToPostfixConverterTest.java


2 // Infix to postfix conversion
3 import java.util.Scanner;
4
5 public class InfixToPostfixConverterTest
6 {
7 public static void main( String args[] )
8 {
9 // get infix expression
10 Scanner scanner = new Scanner( System.in );
11 System.out.println( "Please enter an infix expression:" );
12 StringBuffer infix = new StringBuffer( scanner.nextLine() );
13 System.out.printf(
14 "\nThe original infix expression is:\n%s\n", infix );
15
16 // change from infix notation into postfix notation
17 StringBuffer postfix =
18 InfixToPostfixConverter.convertToPostfix( infix );
19
20 System.out.printf(
21 "The expression in postfix notation is:\n%s\n", postfix );
22 } // end main
23 } // end class InfixToPostfixConverterTest

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 21

Please enter an infix expression:


5+3*6-2

The original infix expression is:


5+3*6-2
The expression in postfix notation is:
5 3 6 * + 2 -

Please enter an infix expression:


(6+2)*5-8/4

The original infix expression is:


(6+2)*5-8/4
The expression in postfix notation is:
6 2 + 5 * 8 4 / -

17.13 Write class PostfixEvaluator, which evaluates a postfix expression such as

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

b) Method calculate, which evaluates the expression op1 operator op2.


c) Method push, which pushes a value onto the stack.
d) Method pop, which pops a value off the stack.
e) Method isEmpty, which determines whether the stack is empty.
f) Method printStack, which prints the stack.
ANS:

1 // Exercise 17.13 Solution:PostfixEvaluator.java


2 // Using a stack to evaluate an expression in postfix notation
3 import com.deitel.jhtp7.ch17.StackInheritance;
4
5 public class PostfixEvaluator
6 {
7 // evaluate the postfix notation
8 public static int evaluatePostfixExpression( StringBuffer expr )
9 {
10 int i, popVal1, popVal2, pushVal;
11 IntegerStack intStack = new IntegerStack();
12 char c;
13
14 expr.append( ")" );
15
16 // until it reaches ")"
17 for ( i = 0; expr.charAt( i ) != ')'; ++i )
18 {
19 if ( Character.isDigit( expr.charAt( i ) ) )
20 {
21 pushVal = expr.charAt( i ) - '0';
22 intStack.pushInt( pushVal );
23 intStack.print();
24 } // end if
25 else if ( !Character.isWhitespace( expr.charAt( i ) ) )
26 {
27 popVal2 = intStack.popInt();
28 intStack.print();
29 popVal1 = intStack.popInt();
30 intStack.print();
31 pushVal = calculate( popVal1, popVal2, expr.charAt( i ) );
32 intStack.pushInt( pushVal );
33 intStack.print();
34 } // end else if
35 } // end for
36
37 return intStack.popInt();
38 } // end method evaluatePostfixExpression
39
40 // do the calculation
41 private static int calculate( int op1, int op2, char oper )
42 {
43 switch( oper )
44 {
45 case '+':
46 return op1 + op2;
47 case '-':

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 23

48 return op1 - op2;


49 case '*':
50 return op1 * op2;
51 case '/':
52 return op1 / op2;
53 case '^': // exponentiation
54 return ( int )Math.pow( op1, op2 );
55 } // end switch
56
57 return 0;
58 } // end method calculate
59 } // end class PostfixEvaluator
60
61 class IntegerStack extends StackInheritance
62 {
63 public int stackTop()
64 {
65 int temp = popInt();
66 pushInt( temp );
67
68 return temp;
69 } // end method stackTop
70
71 public int popInt()
72 {
73 return ( Integer ) super.pop();
74 } // end method popInt
75
76 public void pushInt( int c )
77 {
78 super.push( c );
79 } // end method pushInt
80 } // end class IntegerStack

1 // Exercise 17.13 Solution:PostfixEvaluatorTest.java


2 // Using a stack to evaluate an expression in postfix notation
3 import java.util.Scanner;
4
5 public class PostfixEvaluatorTest
6 {
7 public static void main( String args[] )
8 {
9 // get postfix expression
10 Scanner scanner = new Scanner( System.in );
11 System.out.println( "Please enter a postfix expression:" );
12 StringBuffer postfix = new StringBuffer( scanner.nextLine() );
13 System.out.printf(
14 "\nThe original postfix expression is:\n%s\n", postfix );
15
16 // evaluate postfix expression
17 int answer =
18 PostfixEvaluator.evaluatePostfixExpression( postfix );
19

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
24 Chapter 17 Data Structures

20 System.out.printf( "The value of the expression is: %d", answer );


21 } // end main
22 } // end class PostfixEvaluatorTest

Please enter a postfix expression:


5 3 6 * + 2 -

The original postfix expression is:


5 3 6 * + 2 -
The stack is: 5

The stack is: 3 5

The stack is: 6 3 5

The stack is: 3 5

The stack is: 5

The stack is: 18 5

The stack is: 5

Empty stack
The stack is: 23

The stack is: 2 23

The stack is: 23

Empty stack
The stack is: 21

The value of the expression 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

c) For each minute of the day, consider the following:


If the next customer arrives, proceed as follows:
Say so.
Enqueue the customer.
Schedule the arrival time of the next customer.
If service was completed for the last customer, do the following:
Say so.
Dequeue next customer to be serviced.
Determine customer’s service completion time (random integer from 1 to 4
added to the current time).
Now run your simulation for 720 minutes and answer each of the following:
a) What is the maximum number of customers in the queue at any time?
b) What is the longest wait any one customer experiences?
c) What happens if the arrival interval is changed from 1 to 4 minutes to 1 to 3 minutes?
17.16 Modify Figs. 17.17 and 17.18 to allow the binary tree to contain duplicates.
ANS:

1 // Exercise 17.16 Solution: Tree.java


2 // Definition of class TreeNode and class Tree.
3 package com.deitel.jhtp7.ch17;
4
5 // class TreeNode definition
6 class TreeNode
7 {
8 // package access members
9 TreeNode leftNode; // left node
10 int data; // node value
11 TreeNode rightNode; // right node
12
13 // constructor initializes data and makes this a leaf node
14 public TreeNode( int nodeData )
15 {
16 data = nodeData;
17 leftNode = rightNode = null; // node has no children
18 } // end TreeNode no-argument constructor
19
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 )

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
26 Chapter 17 Data Structures

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 Tree definition
44 public class Tree
45 {
46 private TreeNode root;
47
48 // constructor initializes an empty Tree of integers
49 public Tree()
50 {
51 root = null;
52 } // end Tree no-argument constructor
53
54 // insert a new node in the binary search tree
55 public void insertNode( int insertValue )
56 {
57 if ( root == null )
58 root = new TreeNode( insertValue ); // create the root node here
59 else
60 root.insert( insertValue ); // call the insert method
61 } // end method insertNode
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 )

© 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

1 // Exercise 17.16 Solution: TreeTest.java


2 // This program tests the Tree class. The solution to 20.16 is mostly
3 // found in the code of TreeNode, in package com.deitel.jhtp7.ch17
4 import java.util.Random;
5 import com.deitel.jhtp7.ch17.Tree;
6
7 public class TreeTest
8 {
9 public static void main( String args[] )
10 {
11 Tree tree = new Tree();
12 int intVal;
13 Random randomNumber = new Random();
14 System.out.println( "Inserting the following values: " );
15
16 // randomly generate numbers and insert in the tree
17 for ( int i = 1; i <= 10; i++ )
18 {
19 intVal = randomNumber.nextInt( 100 );
20 System.out.print( intVal + " " );
21 tree.insertNode( intVal );
22 } // end for
23
24 // print each of the traversals
25 System.out.println ( "\n\nPreorder traversal" );
26 tree.preorderTraversal();
27
28 System.out.println ( "\n\nInorder traversal" );

© 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

Inserting the following values:


53 31 6 97 77 8 8 69 3 39

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

Inserting the following values:


98 7 66 4 67 66 19 51 64 49

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:

1 // Exercise 17.17 Solution: Tree2.java


2 // Class Tree2 definition.
3 package com.deitel.jhtp7.ch17;
4
5 class TreeNode2
6 {
7 // public access members
8 public TreeNode2 leftNode;
9 public String data;
10 public TreeNode2 rightNode;
11
12 // initialize data and make this a leaf node
13 public TreeNode2( String value )

© 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

1 // Exercise 17.17 Solution: Tree2Test.java


2 // Program tests the Tree2 class.
3 import java.util.Scanner;
4 import java.util.StringTokenizer;
5 import com.deitel.jhtp7.ch17.Tree2;
6
7
8 public class Tree2Test

© 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

Please enter a string:


I have been inserted into a tree

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:

1 // Exercise 17.19 Solution: Tree.java


2 // Definition of class TreeNode and class Tree.
3 package com.deitel.jhtp7.ch17;
4
5 // class TreeNode definition
6 class TreeNode
7 {

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
32 Chapter 17 Data Structures

8 // package access members


9 TreeNode leftNode; // left node
10 int data; // node value
11 TreeNode rightNode; // right node
12
13 // constructor initializes data and makes this a leaf node
14 public TreeNode( int nodeData )
15 {
16 data = nodeData;
17 leftNode = rightNode = null; // node has no children
18 } // end TreeNode no-argument constructor
19
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 Tree definition
44 public class Tree
45 {
46 private TreeNode root;
47
48 // constructor initializes an empty Tree of integers
49 public Tree()
50 {
51 root = null;
52 } // end Tree no-argument constructor
53
54 // insert a new node in the binary search tree
55 public void insertNode( int insertValue )
56 {
57 if ( root == null )
58 root = new TreeNode( insertValue ); // create the root node here
59 else
60 root.insert( insertValue ); // call the insert method
61 } // end method insertNode

© 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

1 // Exercise 17.19 Solution: TreeTest3.java


2 // Program tests method depth.
3 import java.util.Random;
4 import com.deitel.jhtp7.ch17.Tree;
5
6 public class TreeTest3
7 {
8 public static void main( String args[] )
9 {
10 Tree tree = new Tree();
11 int number;
12 Random randomNumber = new Random();
13 System.out.println( "Inserting the following values: " );
14
15 // create tree of random numbers
16 for ( int i = 1; i <= 10; i++ )
17 {
18 number = randomNumber.nextInt( 100 );
19 System.out.print( number + " " );
20 tree.insertNode( number );
21 } // end for
22

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 35

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
32 System.out.printf( "\n\nTree has a depth of: %d", tree.depth() );
33 } // end main
34 } // end class TreeTest3

Inserting the following values:


50 81 35 65 45 32 82 5 85 71

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

Tree has a depth of: 3

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:

1 // Exercise 17.20 Solution: List.java


2 // Class List2 definition.
3 package com.deitel.jhtp7.ch17;
4
5 // class to represent one node in a list
6 class ListNode
7 {
8 // package access members; List can access these directly
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 )

© 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

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;
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 {

© 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

1 // Exercise 17.20 Solution: ListTest.java


2 // Program recursively prints a list of random numbers backwards.
3 import java.util.Random;
4 import com.deitel.jhtp7.ch17.List;
5
6 public class ListTest
7 {
8 public static void main( String args[] )
9 {
10 List list = new List();
11 int number;
12 Random randomNumber = new Random();
13
14 // create objects to store in the List

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 39

15 for ( int i = 1; i <= 25; i++ )


16 {
17 number = randomNumber.nextInt( 101 );
18 list.insertAtFront( number );
19 } // end for
20
21 list.print();
22 list.printListBackwards();
23 } // end main
24 } // end class ListTest

The list is: 100 42 43 85 6 81 42 71 90 14 24 60 71 36 0 72 22 76 17 59 15 13


90 70

Reverse ordered list: 70 0 9 13 15 59 17 76 22 72 0 36 71 60 24 14 90 71 42


81 6 85 43 42 100

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:

1 // Exercise 17.21 Solution: List.java


2 // Class List and ListNode declarations.
3 package com.deitel.jhtp7.ch17;
4
5 // class to represent one node in a list
6 class ListNode
7 {
8 // package access members; List can access these directly
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

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
40 Chapter 17 Data Structures

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 );
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

© 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

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 // search list for a specifed value
149 public Object search( Object input )
150 {
151 return searchHelper( input, firstNode );
152 } // end method search
153
154 // helper method for searching
155 private Object searchHelper( Object input, ListNode node )
156 {
157 if ( node == null )
158 return null;
159 else if ( input.equals( node.data ) )
160 return node.data;
161 else
162 return searchHelper( input, node.nextNode );
163 } // end method searchHelper
164 } // end class List

1 // Exercise 17.21 Solution: ListTest.java


2 // Program recursively searches a list of numbers.
3 import java.util.Random;
4 import com.deitel.jhtp7.ch17.List;
5
6 public class ListTest
7 {
8 public static void main( String args[] )
9 {
10 List list = new List();
11 int number;
12 Random randomNumber = new Random();
13
14 // create objects to store in the List
15 for ( int i = 1; i <= 25; i++ )
16 {
17 number = randomNumber.nextInt( 101 );
18 list.insertAtFront( number );
19 } // end for
20
21 list.print();
22
23 Object searchResult = list.search( 34 );
24
25 // display result of searching 34

© 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

The list is: 82 41 9 13 72 40 56 88 79 92 33 96 62 47 84 65 83 92 41 11 57 25


43 77 18

Value not found: 34


Value not found: 50
Value found: 72

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:

1 // Exercise 17.22 Solution: Tree5.java


2 // Deleting items from a tree.
3 package com.deitel.jhtp7.ch17;
4
5 // class TreeNode declaration
6 class TreeNode
7 {
8 // package access members
9 TreeNode leftNode; // left node
10 int data; // node value
11 TreeNode rightNode; // right node
12
13 // constructor initializes data and makes this a leaf node
14 public TreeNode( int nodeData )
15 {
16 data = nodeData;
17 leftNode = rightNode = null; // node has no children
18 } // end TreeNode no-argument constructor
19

© 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

128 root = root.rightNode;


129
130 // if the right child is null, set root to the left
131 else if ( root.rightNode == null )
132 root = root.leftNode;
133 else // both children have values
134 {
135 boolean later = false;
136 TreeNode parent = root;
137
138 // find the largest value smaller than the root
139 TreeNode replacement = root.leftNode;
140
141 while ( replacement.rightNode != null )
142 {
143 later = true;
144 parent = replacement;
145 replacement = replacement.rightNode;
146 } // end while
147
148 // create a temporary value
149 TreeNode temp = root;
150
151 // set the root to the replacement node
152 root = replacement;
153
154 // break the old link to the replacement node
155 if ( later )
156 parent.rightNode = replacement.leftNode;
157 else // only occurs if replacement is immediately to the left
158 parent.leftNode = replacement.leftNode;
159
160 replacement.rightNode = temp.rightNode;
161 replacement.leftNode = temp.leftNode;
162 } // end else
163 } // end if
164 else if ( test > d ) // node is to the left of root
165 root.leftNode = deleteNode( root.leftNode, d );
166 else if ( test < d ) // node is to the right of root
167 root.rightNode = deleteNode( root.rightNode, d );
168 } // end method deleteItem
169
170 private TreeNode deleteNode( TreeNode top, int d )
171 {
172 // if the tree is empty
173 if ( top == null )
174 return top;
175
176 int test = top.data;
177
178 // if the top is the value to be deleted
179 if ( test == d )
180 {
181 // if the left child is null, set top to its right

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
48 Chapter 17 Data Structures

182 if ( top.leftNode == null )


183 return top.rightNode;
184 else if ( top.rightNode == null ) // right child is null
185 return top.leftNode; // set top to its left child
186 else // both children have values
187 {
188 boolean later = false;
189 TreeNode parent = root;
190
191 // find the largest value smaller than the top
192 TreeNode replacement = top.leftNode;
193
194 while ( replacement.rightNode != null )
195 {
196 later = true;
197 parent = replacement;
198 replacement = replacement.rightNode;
199 } // end while
200
201 // create a temporary value
202 TreeNode temp = top;
203
204 // set the top to the replacement node
205 top = replacement;
206
207 // break the old link to the replacement node
208 if ( later )
209 parent.rightNode = replacement.leftNode;
210 else // only occurs if replacement is immediately to the left
211 parent.leftNode = replacement.leftNode;
212
213 replacement.rightNode = temp.rightNode;
214 replacement.leftNode = temp.leftNode;
215 } // end else
216 } // end if
217 else if ( test > d ) // node is to the left of root
218 top.leftNode = deleteNode( top.leftNode, d );
219 else if ( test < d ) // node is to the right of root
220 top.rightNode = deleteNode( top.rightNode, d );
221
222 return top;
223 } // end method deleteNode
224 } // end class Tree5

1 // Exercise 17.22 Solution: TreeTest3.java


2 // Program extends a binary tree to allow deletion.
3 import java.util.Random;
4 import com.deitel.jhtp7.ch17.Tree5;
5
6 public class TreeTest3
7 {
8 public static void main( String args[] )
9 {

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 49

10 Tree5 tree = new Tree5();


11 int number;
12 Random randomNumber = new Random();
13 System.out.println( "Inserting the following values: " );
14
15 // create tree of random numbers
16 for ( int i = 1; i <= 20; i++ )
17 {
18 number = randomNumber.nextInt( 100 );
19 System.out.print( number + " " );
20 tree.insertNode( new Integer( number ) );
21 } // end for
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
32 int deleteValue = randomNumber.nextInt( 100 );
33
34 System.out.printf( "\n\nDeleted value: %d", deleteValue );
35 tree.deleteItem( new Integer( deleteValue ) );
36
37 System.out.println ( "\n\nPreorder traversal" );
38 tree.preorderTraversal();
39
40 System.out.println ( "\n\nInorder traversal" );
41 tree.inorderTraversal();
42
43 System.out.println ( "\n\nPostorder traversal" );
44 tree.postorderTraversal();
45 } // end method main
46 } // end class TreeTest3

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
50 Chapter 17 Data Structures

Inserting the following values:


96 57 55 91 35 59 2 3 87 70 45 23 33 77 13 93 80 69 37 57

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:

1 // Exercise 17.23 Solution: Tree.java


2 // Class Tree4 definition.
3 package com.deitel.jhtp7.ch17;
4
5 // class TreeNode definition
6 class TreeNode
7 {
8 // package access members
9 TreeNode leftNode; // left node
10 int data; // node value
11 TreeNode rightNode; // right node
12
13 // constructor initializes data and makes this a leaf node
14 public TreeNode( int nodeData )
15 {
16 data = nodeData;
17 leftNode = rightNode = null; // node has no children
18 } // end TreeNode no-argument constructor
19
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 )

© 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ä.

Kahden ja kolmen välillä lähti kruunajaiskulkue liikkeelle. Eerik


Sparre kantoi omenaa, Hogenskild Bjelke valtikkaa, Niilo
Gyllenstjerna kruunua ja Klaus Fleming miekkaa. Sen jälkeen seurasi
kuningas jalkaisin ja herttua samoin. Kuningatar ajoi vaunuilla,
samoin hänen jälestään leskikuningattaret ja jalo Juhana prinssi ja
viimeksi prinsessat Anna ja Sofia, vaunuilla hekin. Sitten tulivat hovin
herrat ja naiset.

Heti kulkueen saavuttua kirkkoon piti arkkipiispa kruunaussaarnan.


Kun se oli päättynyt, nousi kuningas ja meni pääalttarille. Siellä hän
lankesi polvilleen. Eerik Sparre saneli valankaavan, ja kuningas teki
valan kohotetuin käsin. Sen jälkeen astui esiin Vesteråsin piispa
Bellinus ja pani kruunun hänen päähänsä. Sillaikaa luki arkkipiispa
rukoukset.

Samoin juhlamenoin kruunattiin sen jälkeen kuningatarkin.


Kuningas istui paikalleen valtaistuimelle, ja Yrjänä Posse kantoi esiin
valtakunnan lipun, johon hän tarttui oikealla kädellään.

Herttuan olisi nyt ollut tehtävä läänitysvalansa, ja valtaistuimen


eteen asetettiin samettityyny, jolle hänen olisi ollut polvistuttava.
Mutta Kaarle kieltäytyi.

"Sellainen on vanha tapa", sanoi Sigismund.


"En polvistunut teidän majesteettinne isänkään edessä", vastasi
Kaarle varmasti.

Sigismund synkistyi, hän etsi vastausta, mutta herttua oli jo


ennättänyt ottaa päästään kultakruunun ympäröimän hattunsa ja
pani sen tyynylle. Itse astui hän esiin, tarttui lipputankoon ja teki
valan, jonka kaavan Eerik Sparre hänelle saneli.

Juhana herttua ja valtaneuvokset tekivät sitten


uskollisuudenvalansa, jonka jälkeen juhlakulkue lähti kirkosta ja
palasi linnanjuhlaan. Siellä tekivät muut säädyt uskollisuudenvalansa.

Lopuksi luettiin kuulutus, jonka mukaan kuningas aikoi lähteä


Puolaan ja valtakunnan hallitus oli jäävä herttuan ja neuvoston
haltuun.

Ja sitten oli linnassa päivittäin vastaanottoja, mutta lisäksi suuria


vieraspitoja useaan kertaan viikossa.

Kuningatar oli liian heikko tekemään "les honneurs", mutta Anna


neiti teki sen hänen sijastaan, ja kaukaa sai etsiä rakastettavampaa
ja kohteliaampaa emäntää.

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ä…

Toinenkin Anna herätti hovissa suurta huomiota. Kustaa Banér oli


tuonut emäntänsä ja tyttärensä Upsalaan, ja molemmat nuoret
neitsyet luettiin pian ylistetyimpäin kaunotarten joukkoon. Erittäinkin
Anna niitti voittoja; hänen pohjoismaille eduskuvallinen kauneutensa,
vaaleat kutrinsa, suuret siniset silmät ja raitis hipiänsä, mutta kenties
enimmän hänen eloisa vilkkautensa ja raikas naurunsa veti kaikkien
silmät puoleensa ja valloitti kaikkien sydämet.

Ulkomaalaiset eivät voineet kuunaan katsella häntä kyllikseen.


Mutta erittäinkin kaksi miestä, joilla oli sangen erilainen elinasema,
omistivat hänelle palvontansa ja ihailunsa. Toinen heistä oli Kustaa
herttua, Sofia prinsessan poika, toinen oli käsisihteeri Potsmutschi,
joka nyt oli kääntänyt purjeensa uusille vesille.

Hänen asemassaan oleva ruotsalainen ei olisi rohennut lähennellä


niin korkeasukuista neitsyttä, mutta koreasti sonnustetun,
tavattoman kauniin puolalaisen, jonka käsivarteen kuningas usein
nojasi ja jolla hovissa näytti olevan suuri vaikutusvalta, hänen
palvontansa oli imartelevaa, samalla kuin keskustelu hänen
kanssansa huvitti. Hän oli paljon matkustellut, käynyt monissa
eurooppalaisissa hoveissa ja osoitti sellaista olosuhteiden
tuntemusta, joka ei yleensä tule maallikkojen osaksi.

Nuori herttua puolestaan oli äsken palannut Italianmatkalta. Oli


hänkin nähnyt yhtä ja toista, ja molemmat koettivat kilvan näyttää
tietojaan. Mutta sitä ei voinut auttaa, että ruotsalainen jäi alakynteen
ja puolalainen aina sai viimeisen sanan.

Kustaa herttua olisi tuskin koskaan antautunut otteluun, jollei


häntä olisi vallannut raivoisa mustasukkaisuus sitä kohtaan, joka
uskalsi kilpailla hänen kanssaan Anna Banérin suosiosta. Hän oli
ykskaks heittänyt kaikki kunnianhimoiset aikeensa yli laidan mereen;
hän rakasti ensi kertaa elämässään, rakasti niin intohimoisella
kiihkeydellä kuin saattoi odottaa hurjapäisen Maunu Saksilaisen
pojalta.

Kaikki tämä tapahtui nuorten kieppuessa karkelossa linnansaleissa.


Siellä uhkui nauru ja pilapuheet kaikkien huulilla, mutta vakavat,
surulliset ajatukset piilivät monen sydämessä ja mielessä.

*****

Herttuan luo oli kutsuttu vieraspitoihin kaikki neuvosherrat, niiden


joukossa Kustaa Banérkin perheineen.

"Minä pelkään, millä mielellä herttuatar on minua kohtaan", sanoi


Anna. "Hän ei varmaankaan ole unhoittanut sitä, että kieltäysin, kun
hän minua kutsui seurakseen Nyköpingiin."

"Silloin täytyy hänen muistaa sekin, että minä tarjouduin


menemään sijastasi", vastasi Märta.

"Herttuatar kelvannee järjestyksen esikuvaksi", sanoi Kristina


rouva.
"Hänen kotinsa on hyvä koulu nuorille tytöille."

"Tahdotko, rakas äiti, lähettää meidät tosiaankin sinne?"

Ei, sitä ei Kristina rouva tahtonut. Hän syleili tyttäriään ja kehoitti


heitä esiintymään erittäin vakavasti tällä vierailumatkalla.

Herttuan luo oli kokoontunut lukuisia vieraita, ja Kaarle itse otti


Kustaa herran vastaan vanhana hyvänä ystävänään; heitä yhdistivät
tällä hetkellä samat harrastukset, he pyrkivät samaan maaliin. Hän
vei hänet huoneeseensa, johon useita neuvosherroja oli kokoontunut
neuvotteluun.
Suorana ja jäykkänä kuten tavallisesti tervehti herttuatar viimeksi
saapuneita vieraitaan; hän tervehti vain Kristina rouvaa ja Märtaa,
Annaa hän ei ollut näkevinäänkään.

Tämä istuutui siihen syrjäiseen paikkaan, joka hänelle oli osoitettu,


ja päätti lujasti, ettei antaisi mielensä lannistua.

Muutamien minuuttien kuluttua tuli neiti Kätchen; siveästi


tervehdittyään kaikkia läsnäolevia istuutui hän Annan viereen, ja
nämä molemmat olivat pian kietoutuneet vilkkaaseen keskusteluun.

Mutta se ei miellyttänyt herttuatarta, joka oli päättänyt rangaista


Anna Banéria heti tilaisuuden saatuaan. Tämä sai istua yksikseen
nurkassa häpeämässä, se oli aivan parahiksi. Ja sentähden
huudettiin pikku Katarina pois, hän sai istua äitinsä vieressä.

Se oli tahallinen loukkaus. Mutta Kristina rouva heitteli tyttäreensä


kehoittavia katseita, ja tämä puri hampaansa yhteen ja koetti
näyttää iloiselta.

Silloin astui saliin Sofia herttuatar poikansa keralla.

Kristina herttuatar istutti hänet heti viereensä. Sofia rouva oli


omituinen, hiljainen rouva, mutta hän piti siitä, että hänelle
osoitettiin asianomaista kunnioitusta.

Hänen poikansa virkkoi hilpeästi, että kun hän ei ymmärtänyt eikä


harrastanut politiikkaa, jäi hän mieluummin herttuattaren luo, ja sen
jälkeen hän muitta mutkitta istuutui Anna Banérin viereen.

"Mikä onni, että tulimme tänne juuri tänä iltana!"


"Erittäinkin minulle, kun minun ei tarvitse istua yksin nurkassani",
vastasi Anna veitikkamaisesti hymyillen.

"Kuinka niin nurkassanne?"

"Niin, rangaistukseksi, sillä herttuatar on minulle vihoissaan!"

"Sen parempi, silloin kenties saan pitää teidät yksinäni."

"Luulenpa, että hän pian kutsuu teidät täältä!"

"Se on helpommin sanottu kuin tehty!"

"Kuulostaa siltä, ettette tunne herttuatarta."

"No, surkupa hänestä! Mutta se surettaisi minua iät kaiket, jollen


saa sanoa teille, mikä on painanut sydäntäni."

"Mitähän se on?"

"Jos voisin tekeytyä näkymättömäksi tämän joukon keskellä,


lankeaisin jalkoihinne, tarttuisin käteenne ja huudahtaisin: Anna,
minä rakastan, jumaloin teitä!"

"Oh, mitä ajattelette!"

"Että olette rakastettavin, suloisin, kaunein, ihastuttavin tyttö


maailmassa, ja että rakastan teitä mielettömästi, hulluuteen saakka,
niin etten voi elää ilman teitä."

"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!"

"Jos virkatte vielä sanaakaan, pakoitatte minut nousemaan!"

"Jos teette sen, vannon ritarikunniani kautta, että olette nähnyt


minut viimeisen kerran!"

"Kuinka kiihkeä olette!"

"Sitä en voi auttaa, se on isän perintöä. Vastaa nyt minulle


mutkittelematta, rakastatko minua?"

"En vielä ainakaan", vastasi Anna äänettömyyden jälkeen.

"Mutta se on mahdollista… vastaisuudessa?" Nuori mies tahtoi


tarttua hänen käteensä.

"Kaikki katsovat meihin!"

"Rukoilen teitä, vastatkaa, vastatkaa!"

"Kuka voi sanoa mitä tulevaisuudessa tapahtuu."

"Hyvästi, neitsyt!" Hän nousi kiihkeästi

"Ettekö tahdo kuulla mitä minulla oli lisättävää…"

Toinen istuutui jälleen.

"Jos hillitsette kiihkeää luontoanne!"

"Sinun tähtesi, Anna, voisi minusta tulla vaikka karitsa!"

"Siitä pitäisin paljon", sanoi Anna hymyillen suloisinta hymyään.


"Huomenna tulen isäsi luo!"

"Tiedän mitä hän vastaa."

"No?"

"Anna on äsken täyttänyt kuusitoista, kukaan tyttäristäni ei saa


mennä naimisiin ennenkuin on täyttänyt kaksikymmentä."

"Oh, se olisi julmaa!"

"Odottakaas, isäni kysyisi lisäksi: kuinka vanha te olette, nuori


herraseni?"

"Täyttänyt yhdeksäntoista vuotta."

"Tulkaa sitten uudestaan kolmenkolmatta vanhana, silloin saatte


vastauksen."

"Ja millainen silloin on vastaus?"

"Luulen, että se on suotuisa", sanoi Anna melkein kuiskaten.

"Kiitos! En virka mitään, ennenkuin olen saavuttanut aseman


elämässä."

Mutta nyt tapahtui jotakin, mitä ei kukaan ollut aavistanut. Sofia


rouva oli salavihkaan tarkoin seurannut rakasta poikaansa;
äidinvaisto sanoi hänelle mitä oli kyseissä, ja hän nousi nopeasti
mennen nuorten luo.

"Se on hän!" sanoi vanhus hiljaa pojalleen.

"Niin, äiti, se on hän", sanoi poika yhtä hiljaa.


Sofia tarttui Annan käteen ja taputti sitä.

"Kaunis, sangen kaunis", sanoi hän häntä katsellen.

Onneksi astui herttua samassa toisten herrojen kera sisään.


Herttua otti heti sisarensa haltuunsa, ja Anna sai tilaisuuden paeta
äitinsä luo.

Hän kertoi tälle kaiken, sillä olihan äiti sen ilmankin arvannut.
Eikä Kristina rouva hidastellut ilmoittaa asiaa miehelleen.

"Anna on tehnyt oikein!" sanoi Kustaa herra. "Nuori herra on


ajattelematon nuorukainen, josta en paljoa odota, mutta aikapahan
näyttää."

Kaikki tiesivät, vaikkeivät olleet tietävinään, että Kustaa herttua oli


tunnustanut Anna Banérille rakkautensa koko seuran ollessa läsnä.
Herttuatar oli suutuksissaan. Samainen Anna, josta hän kerran oli
armossaan pitänyt, oli aina saanut hänelle aikaan paljasta harmia.
Hän ei voinut kieltää, että hän itse oli syypää tähän viimeiseen; juuri
se, minkä hän oli aikonut tytön alennukseksi, oli koitunut
ylennykseksi, ja lopulta tämä vielä saattoi joutua kuninkaalliseen
sukuun.

"Syytä itseäsi", sanoi herttua nauraen. "Mutta ei hän toisekseen


siellä vielä ole."

"Aiotko kenties estää?"

"En suinkaan, päinvastoin; kansa pitäisi siitä, että saisi jotakin


kaunista katsellakseen."

Herttuatar puri huultaan ja katsoi viisaimmaksi vaieta.


*****

Kruunausjuhlallisuuksien ajaksi sattuivat Distingin markkinat.


[Saanut varmaankin alkunsa muinaisskand. Dis-haltiattaren
kunniaksi pidetyistä käräjistä.] Läheltä ja kaukaa saapui yhtä mittaa
kauppiaita, käsityöläisiä, ostajia ja myyjiä. Torille oli pystytetty
markkinakojuja pitkiin riveihin, joissa turkkeihinsa kääriytyneet
kauppamiehet myivät kankaita, korukaluja, kulta- ja hopeaesineitä,
kupari-, läkki- ja tinatavaroita, aseita, pajakaluja, turkiksia ja
tuhansia muita esineitä, jotka tuottivat kiiltävää ja kilisevää.
Kalatorilla myytiin maan ja karjan tuotteita ja veden antimia, mutta
siellä liikuskeli ainoastaan pikku eläjiä. Ylhäiset menivät suurelle
torille, jossa saivat tunkeilla taajojen väkijoukkojen lävitse.

Sinne lähtivät eräänä markkinapäivänä myös sisarukset Anna ja


Märta Banér. Torilla tapasivat he monta ystävää ja tuttavaa ja
ostelivat monia pikkuesineitä, jotka heti jakoivat köyhille
kerjäläislapsille. Märta oli koonnut heitä koko parven ympärilleen ja
tyydytti heidän toiveensa niin pitkälle kuin hänen varansa riittivät.

"Antakaa minulle jotakin jalkaani", huusi muuan pikku ryysyläinen.

"Minulle myös, minulle myös!" säestivät toiset.

Anna seisoi kappaleen matkan päässä asesepän myymäkojulla.


Hän oli ostanut harvinaisin heloin ja kaiverruksin koristellun tikarin,
jonka aikoi antaa vanhimmalle veljelleen. Silloin nyki Märta häntä
käsivarresta.

"Katsos raukkoja", sanoi hän, "he käyvät melkein avojaloin


paksussa lumessa. Eikö se ole hirveää?"
"Menkäämme suutarille ja ostakaamme heille jalkineet… tule,
ottakaamme lapset mukaan."

Märta oli ihastunut, eivätkä lapset suinkaan vähemmän.


Palvelijattaren opastamana menivät he suutarille, Anna ja Märta
edellä, jälestä lapsia kymmenkunta. Kukaan ei pannut merkille
upeasti puettua herrasmiestä, joka seurasi lapsia.

Suutarin naama loisti ilosta, kun hän kuuli mistä oli kysymys. Hän
lupasi hyvää tavaraa huokeaan hintaan.

Valittiin heti jalkineet kaikille pienokaisille, ja monin suurkiitoksin


riensivät he iloisina ja onnellisina tiehensä.

Mutta kun Annan piti ottaa kukkaronsa maksaakseen, olikin se


poissa.
Oliko se varastettu, vai oliko hän unhottanut sen asesepälle?

"Mitä nyt teemme?" kysyi Märta pelästyneenä.

"Ottakaa minun kukkaroni", kuului ääni heidän takaansa, ja kun he


kääntyivät, näkivät he hymyilevän, kumartelevan Potsmutschin.
Puolalaisella oli kädessään kukkaro, jonka hän tahtoi antaa Annalle.

Anna loi häneen kylmän ja ylvään katseen. "Oletteko seurannut


tänne jälestämme?"

"Niin, toivoin voivani olla hyödyksi."

"Sellaisista pikku asioista selviydyn kyllä itsekin", sanoi Anna


vetäisten rannerenkaansa ranteestaan. "Tämä vastaa velkaani monin
kerroin", sanoi hän. "Ottakaa se, huomenna lunastan sen."
Suutari tarkasti kalleuden ja kumarsi aivan maahan; hän ei
tarvinnut lainkaan panttia…

"Miksi en saanut tehdä teille pikku palvelusta?" kuiskasi


puolalainen.

"En ota vastaan mitään palveluksia muukalaisilta", vastasi ylväs


neitsyt tarttuen sisarensa käsivarteen ja poistuen puodista.

Puolalainen seurasi jälestä.

Aivan puodin edustalla he kohtasivat kaksi ylioppilasta, jotka olivat


sangen riemahtelevalla markkinatuulella.

"Kas, kuinka kauniita tyttöjä!"

"Pankaamme tasan!"

Näillä tuumin aikoivat he eroittaa sisarukset toisistaan.

"Uskaltakaapas vain koskea heihin", huusi palvelijatar ja alkoi


peitota molempien ylioppilasten selkänahkaa.

"Maltas sinä", huusi heistä toinen ja tarttui naiseen. Mutta tämä oli
yhtä väkevä kuin urhokaskin ja antoi iskun iskusta.

"Vetäkää miekkanne ja puolustakaa meitä", huusi Anna


Potsmutschille, mutta käännyttyään hän huomasikin tämän
kadonneen.

"Hylkiö!" jupisi hän, ja nopeasti kuin ajatus vetäisi hän tikarin


hameensa taskusta.
"Hyvin tehty!" huusi toinen ylioppilaista. "Noin kaunis ja sittenkin
niin sisukas!"

"Mutta kuinka voi ruotsalainen ylioppilas niin unhottaa kunnian


lait, että käy turvattomain naisten kimppuun?" kysyi Anna.

"Onhan teillä turvanne! Jalo neitsyt, tahdotteko sanoa minulle


nimenne?" sanoi ylioppilas.

"Anna Banér."

"Valtaneuvoksen tytär?"

"Niin."

"Sallitteko meidän saattaa teidät kotiin."

"Päästäkää ensin irti palvelijattareni."

He täyttivät heti hänen käskynsä.

"Eiköhän ole parasta, että pujahdamme tiehemme?" kysyi Märta.

"Ei, meidän on näytettävä, että luotamme heihin."

Niin lähdettiin kotimatkalle. Ylioppilaat olivat neitsytten


suojelusvartiona, ja se oli hyvin tarpeen, sillä alkoi hämärtää, ja
paljon hylkyväkeä liikuskeli kaduilla. Erotessa kumarsivat he syvään,
sisarusten rientäessä pihalle portista, joka heti sulkeutui heidän
jälkeensä.

"Sellainen tyttö!"

"Lähtekäämme juomaan hänen maljansa!"


"Ei, minä lähden kotiin unelmoimaan hänestä."

*****

Kruunajaisten jälkeen seurasi juhlia perätysten. Päivälliset ja


hovitanssiaiset vaihtelivat keskenään, eikä herttuakaan kieltäytynyt
olemasta mukana.

Anna Banérin reipas menettely oli tullut tunnetuksi, ja siitä


puhuttiin paljon. Häntä ylistettiin yhtä paljon kuin halveksittiin
Potsmutschin arkaa pelkuruutta. Turhaan tämä puolustautui sillä,
että oli ollut aseeton ja sentähden rientänyt noutamaan sotamiehiä
avuksi. Kukaan ei kallistanut sille korvaansa, ja pilkkasanat satelivat
hänen ympärillään.

Eräässä linnan juhlassa olivat Kustaa Brahe ja Kustaa herttua


härnäilleet häntä, ja hän huusi suutuksissaan: "Kolmea vastaan
kerrallaan en ole koskaan taistellut, mutta kahdesta ruotsalaisesta
aina selviän, olkootpa he kuinka pöyhkeitä ja ylväitä tahansa."

"Varokaa, ettette lupaa enempää kuin voitte täyttää!" puuskahti


Kustaa Brahe.

"Toivoisin, että minut käsitetään sanalleen."

Kustaa herttua ilmoitti tästä Anna Banérille. Hän pyysi neitsyeltä


lupaa vaatia hävyttömän puolalaisen kaksintaisteluun.

"Ei", vastasi Anna varmasti. "Tahdon itse rangaista häntä."

"Millä tavoin?"

"Antaa sen jäädä salaisuudekseni!"


Annalla oli sen jälkeen pitkä keskustelu isänsä kanssa, hän puhui
puolalaisen sietämättömästä julkeudesta ja että Kustaa herttua
halusi manata hänet kaksintaisteluun.

"Jollei se olisi moiselle hylkiölle liian suuri kunnia, rankaisisin itse


häntä", vastasi kreivi.

"Sinä, rakas isä! Ei, ei, tyttäresi voi itsekin kostaa puolestaan."

"Millä tavoin?"

"Näinä päivinä pidetään täällä turnajaiset, ja sinä olet itse


opettanut minulle miten vihollinen syöstään satulasta; ei suinkaan
sinustakaan Potsmutschi istu siinä niin lujassa."

"Ei, kautta taivaan!" vastasi Kustaa herra hymyillen. "Ja totta on,
ettei häntä voisi pahemmin nolata. Mutta pelkään, ettei äitisi tule
kuunaan suostumaan."

"Rakas isä, hän ei saa tietää mitään ennenkuin olen voittanut."

"Oletko varma, että turnajaisista tulee mitään?"

"Aivan varma; Potsmutschi kertoi minulle kuulleensa siitä


kuninkaalta itseltään; hän aikoo olla mukana ja pyysi, että saisi
kantaa minun värejäni."

"Häpeämätön!"

"Minä vastasin, että ne on jo saanut toinen."

"Milloin turnajaiset ovat?"

"Ensi viikolla."
"Hyvä, siihen mennessä harjoittelemme." Niin he tekivätkin.

Sigismund oli ihastunut turnajaisten hommaamiseen. Mitään


säästämättä koetettiin ne saada niin loistaviksi kuin mahdollista. Ne
oli pidettävä kaupungissa markkinatorilla, jonka siihen täytyi olla
tyhjennetty. Rata aidattiin, laitettiin lavat hoville, palkintotuomareille
ja lukuisille muille katsojille.

Vihdoin oli päivä käsissä, kirkas, keväisen päiväpaisteinen päivä.


Molemmat hovit tulivat suurella loistolla ja upeudella, sen jälkeen
leskikuningattaret ja korkeat vieraat, naiset vaunuin, herrat ratsain,
kaikilla lukuisat ja loistavat seurueet. Jalokivet säkenöivät, kulta
välkkyi, silkki kahisi, liehuivat sulkatöyhdöt ja korukirjailut
kimmelsivät. Silkkisametti solui kaikissa väreissä vartaloilla, milloin
hienoilla ja solakoilla, milloin jyrkeän tanakoilla, ja saattoi tuskin
arvioida sitä kallisarvoisten turkisten paljoutta, joka oli katseltavana.

Mutta kauniimpi, loistavampi kaikkea muuta oli talvipäivän


kevätkirkas aurinko, joka siroitteli säderunsauttaan lukemattomille
välkkyville kypäreille, haarniskoille ja keihäille ja ilosta loistaviin
ihmissilmiin.

Yleisen tavan mukaan astuivat esiin airuet ilmoittaen missä


järjestyksessä taistelijat esiintyivät, ja torventoitotuksin julistettiin
aseleikit alkaneiksi.

Ruotsalaiset ritarit taistelivat vastatusten, kukin kantaen


sydämensä naisen värejä, kaikki osoittaen suurta taitavuutta ja
saavuttaen yleistä hyväksymistä. Kuningatar jakoi itse palkinnot ja
koristi monen ritarin pään tuorestuoksuisin laakerein, kun voittajat
polvistuivat hänen eteensä ja laskivat miekkansa maahan.
Oli herättänyt hieman kummastusta ja paljon naurua se, ettei
kukaan puolalaisista herroista ottanut osaa turnajaisiin. Ruotsalaiset
kuiskailivat naureskellen keskenään, puolalaisten arkuus ja heikkous
miekkailutaiteessa oli yleisesti tunnettu.

Leikki läheni loppuaan, eikä luultu enää kenenkään ilmoittautuvan


kilpailuun, kun muuan puolalainen ratsasti radalle kallisarvoisissa
varustuksissaan ja alaslasketuin kypärinsilmikoin ja kauniilla
latinankielellä vaati taisteluun sen ritarin, joki kantoi olallaan
vaaleanpunaista nauharuusuketta.

Heti avasivat ulkopuolella odottelevat kujan, ja radalle, lasketti


ilmeisesti sangen nuori ratsastaja.

Hän kumarsi kohteliaasti, kääntyi sen jälkeen vastustajaansa ja


sanoi nauharuusukkeeseen viitaten:

"Ottakaa se, jos voitte!"

"Suuri Jumala!" kuiskasi Kristina rouva tyttärelleen. "Se on Anna!"

"Mahdotonta, rakas äiti!"

"Sanon sinulle, että hän se on."

Puolalainen tuijotti ratsastajaan. "Poikanen vain!" sanoi hän.


"Syyttäköön itseään!" Näin jupisten ratsasti hän radan äärimäiseen
päähän.

Nuori ruotsalainen hoiti ihmeteltävän helposti hevostaan ja teetti


sillä muutamia kauniita pyörähdyksiä.
Puolalainen istui jäykkänä satulassaan, ruotsalainen keveästi ja
vapaasti.

Merkin saatuaan syöksähtivät he toisiaan vastaan. Peitsenisku


vain, ja puolalainen lennähti pallona satulasta radalle.

Nuori ruotsalainen, joka oli aivan vahingoittumaton, hyppäsi heti


alas ratsailta ja riensi nostamaan kaatuneen vastustajansa kypärin.

Kyllähän Potsmutschi tunnettiin.

Sen jälkeen kohotti ruotsalainen oman kypärinsä, ja aalloten


valahtivat hänen tuuheat, vaaleat kutrinsa alas ritarin puvulle.

"Neitsyt Anna Banér!" kajahti innostunut huudahdus.

Silloin otti hän pienen hajuvesipullon ja antoi sen kaatuneelle. "Kas


tässä, otin sen mukaani teitä varten!" Näin sanoen hän riensi
kuningattaren luo ja polvistui. Kuningatar nosti hänet pystyyn ja
syleili häntä.

Suosiohuudot eivät tahtoneet ottaa loppuakseen, ja nolattuna ja


nöyryytettynä hiipi Potsmutschi tiehensä.

Kustaa Brahen katse etsi melkein vaistomaisesti prinsessaa; hän


näki sanomatonta halveksumista siinä katseessa, jonka tämä loi
puolalaiseen, ja epäluulot hälvenivät kuin savu tuuleen, ja hän päätti
heti Tukholmaan palattua puhua ratkaisevan sanan hänen kanssaan.

Vihdoinkin juhlat lähenivät loppuaan. Herttua sanoi kylmät


jäähyväiset ja palasi Nyköpingiin. Kaksi päivää sen jälkeen palasi
kuningas Tukholmaan, ja pian oli Upsala päässyt rauhaan
vieraistaan.
9.

KATOLINEN HALLITUS.

Neuvosto oli pelännyt herttuaa, ja lujalla tahdollaan oli Kaarle


saanut hyväksytyksi Upsalan päätökset.

Sigismund ei ollut ryhtynyt mihinkään uskottujensa, Malaspinan,


sihteeri I. Bultin ja Tarnovskin kanssa. Nämä neuvoivat taipumaan
olosuhteiden pakosta, aina siinä takatarkoituksessa, että mitä
annettiin toisella kädellä, se saatettiin toisella ottaa takaisin. Kunhan
vain olisi päästy herttuasta, kylläpähän sitten aina neuvoston kanssa
selvittäisiin!

Neuvoston joukossa oli kuninkaalla vain yksi ainoa ystävä, Klaus


Fleming. Hän oli mainio sotapäällikkö, ovela ja tarkka
suunnittelemaan, mutta samalla kursailematon ja karkea koko
olemukseltaan. Kun hän oli lisäksi luihu luonnoltaan, miellytti häntä
seista kuninkaan ja hänen katolisen joukkionsa suojelusmuurina.
Heidän ei auttanut muuta kuin turvautua kaikessa häneen, joka tunsi
ruotsalaiset olosuhteet.

Kuningas, Malaspina, Tarnovski, kaikki kääntyivät hänen


puoleensa, ja hän osasi tehdä itsensä välttämättömäksi kaikille.
Malaspina neuvotteli hänen kanssaan, ja Klaus herra, joka oli
herttuan verivihollinen, sanoi, että kunhan vain siitä "pirusta"
vapauduttiin, saatiin tehdä mitä tahdottiin. Hän meni takuuseen,
etteivät neuvosherrat sitten uskaltaneet hiiskahtaakaan.

Ja tästä rauhoittuneena päätti pappisvaltias antaa roomalaisen


kirkon siunauksen virrata tulvanaan kerettiläisten maahan.
Sigismund antoi heti suostumuksensa, hän oli pakoitettuna tehnyt
sitoumuksensa eikä ottanut sen rikkomista niin tunnolleen.

Lofön kirkko vihittiin heti katoliseen jumalanpalvelukseen;


Tukholmassa ostettiin tähän tarkoitukseen suuri talo, Vadstenan
luostariin vihittiin uusi abbedissa ja kaikki poistetut katoliset menot
otettiin jälleen käytäntöön. Tukholman linnankirkko jätettiin
katolisten pappien huostaan, ja muissa pääkaupungin kirkoissa
häirittiin monin tavoin luterilaista jumalanpalvelusta. Siitä valitettiin
kuninkaallekin, mutta hän antoi ainoastaan kierteleviä tai äreitä
vastauksia.

Pääsiäisen lähetessä tahdottiin yleisölle tarjota jotakin uutta.


Haalittiin sieltä täältä kokoon kaksitoista ryysyistä kerjäläistä, jotka
olivat edustavinaan kahtatoista opetuslasta. Ja linnankirkossa
kuningas sitten pesi ja kuivaili heidän jalkojaan. Tämän vanhan
tavan oli osoitettava kansalle, kuinka nöyrä ja kristillismielinen
heidän kuninkaansa oli. Kerjäläiset olivat tyytyväiset runsaaseen
ateriaan, jonka saivat palkakseen, mutta yleisössä ilveily herätti
naurua.

Mutta Malaspina tahtoi tehdä valloituksiaan rynnäköllä, ja


sentähden annettiin isku toisensa jälkeen. Pitkänäperjantaina
haudattiin vanhan tavan mukaan puukuva, joka edusti Kristuksen
persoonaa. Papit toimittivat nämä pyhät maahanpaniaiset suurella
juhlallisuudella, lauluin ja suitsutuksin, ja suunnattomat
kansanjoukot virtailivat katselemaan.

Nyt alkoivat jo pormestarit ja raatimiehet heristellä korviaan. Tämä


meni melkein liian pitkälle.

Mutta ei mitta ollut täysi vieläkään.


Pääsiäisaamuna neljän aikaan, kun monet vielä makasivat
suloisinta untaan, ammuttiin linnanpihassa useita tykinlaukauksia, ja
sinne asetetut heitukat ammuskelivat hyvän aikaa käsipyssyillään.

Kaupungissa syntyi oikea pakokauhu, puolialastomat ihmiset


harppailivat pitkin katuja. "Ryssät ovat kimpussamme! Ryssät ovat
kimpussamme!" huudettiin ja paruttiin kaikkialla. Äidit tulivat lapset
käsivarsillaan ja kaatuivat kadulle tainnoksiin.

Toiset luulivat valkean olevan valloillaan ja riensivät pelastamaan.

Mutta kun asian oikeasta laidasta päästiin perille, silloin muuttui


pelästys syväksi suuttumukseksi. Yksin tyynimmätkin murisivat
tyytymättöminä. Tällaista elämää ei saattanut sietää.

Puolipäivä-jumalan palveluksessa kiitti Schepperus Jumalaa siitä,


että paavilliset eksytykset nyttemmin olivat niin tunnetut, että niille
nauroivat lapsetkin. Edelleen kiitti hän siitä, että kristitty saattoi
sanasta saada parempaa lohdutusta kuin paavilaisten turhamaisista
näytelmistä ja kuolleista kuvista. Hän surkutteli kuningasta ja
kuningatarta, jotka olivat eksytetyt, samoin niitä kahtatoista
kerjäläistä, jotka olivat antautuneet jumalattomaan jalkojen pesuun
ja siten luopuneet evankelisesta uskostaan.

Schepperuksen hyökkäykseen vastasi katolinen pappi Justus


toisena pääsiäispäivänä Linnankirkossa selittäen, ettei koko Svean
valtakunnassa ollut kuuteenkymmeneen vuoteen ollut ainoatakaan
oikeaa pappia; viimeinen arkkipiispanvaali oli ainoastaan
merkityksetön seremonia j.n.e.

Neljäntenä pääsiäispäivänä vastasi Schepperus Suurkirkossa ja


vertasi silloin katolista seurakuntaa Belialiin ja sen kirkkoa Babelin
porttoon.

Nyt paloi sota ilmiliekein, saarnastuoleista purkivat protestantit ja


katoliset toisilleen kaiken sapen, mikä kiehui heidän sisällään; eivät
he enää saarnanneet rauhan ja sovinnon sanomaa, vaan
leppymättömän vihan ja koston oppia.

Sigismund kirjoitti heti arkkipiispalle; hänelle kuului tämän


vallattomuuden hillitseminen.

Angermannus selitti Tukholman papeille, kuinka epäkristillisesti he


olivat käyttäytyneet, ja nämä lupasivat vastedes olla puuttumatta
persoonallisuuksiin. Ja niin palasi toistaiseksi ainakin näennäinen
tyyneys.

*****

Vierasten joukossa Upsalassa oli ollut myös Brandenburgin


rajakreivi. Hän oli jo saapumisestaan saakka omistanut Anna
prinsessalle palvontansa, mutta kukaan ei ollut kiinnittänyt siihen
huomiotaan.

Tukholmaan saavuttua pyysi hän kuninkaalta prinsessan kättä, ja


kuningas lupasi puhua hänen puolestaan.

Mutta ennenkuin tämä oli vielä tapahtunut, lähetti joku


tuntematon henkilö prinsessalle kirjeen ilmoittaen, että Kustaa Brahe
piti rikollista yhteyttä erään porvarillissyntyisen naisen kanssa; mutta
ei siinä kyllin, eräs nainut jalosukuinen rouva oli lisäksi hänen
salainen rakastajattarensa. Viimeisen ilmiannon todistukseksi seurasi
muutamia kirjeitä Kustaa herran omasta kädestä. Anna tunsi
käsialan, mutta näin suurta petollisuutta ei hän ollut odottanut.
Hänen sydämensä kutistui kokoon, eikä hän tiennyt, voiko enää
elääkään niin suuresti petyttyään.

Muutaman päivän kuluttua esitti Sigismund rajakreivin kosinnan ja


puhui, miten tämä oli mieltynyt ja ihastunut prinsessaan.

Anna hämmästyi, mutta vastasi heti: "Rajakreivi on itse tuonut


tänne tiedon suuresta perinnöstä, jonka vihdoin olemme saaneet
isoäidiltämme Bona Svorznalta."

"Siitä saamme kiittää hänen pyhyytensä mahtavaa vaikutusta",


lisäsi
Sigismund vilkkaasti.

"Aivan niin, mutta etkö luule, että rajakreivi juuri sentähden…?"

"Oh, se on arvoton ajatus."

"Jollei se ole hänen, on se paavin lähettilään."

"Et tiedä kuinka väärin teet hänelle. Mutta mitä minun on


vastattava rajakreiville?"

"Sellainen liitto on mahdoton välillämme."

"Miksi niin?"

"Unhotat meidän eri uskontomme."

"Rakas sisareni", sanoi Sigismund tarttuen hänen käteensä,


"olemme toivoneet, että rukouksistamme heltyisit ja kääntyisit
ainoaan autuaaksitekevään kirkkoon."

"Sentähden kai jo Puolassa eroititte evankelisen pappinikin."


"Täytyihän minun veljenäsi ajatella iäistä autuuttasi."

"Tahdon tulla autuaaksi omalla uskollani."

"Mutta rajakreivi…"

"Odotas! Taannoin puhuit suuresta vajauksesta valtiorahastossa."

"Sitä ajattelen alinomaa; olen lainannut siitä enkä näe mitään


mahdollisuutta maksamiseen."

"Voit tehdä sen, jos luovutan sinulle osani neapelilaisista


alusmaistani!"

"Tahdotko tehdä sen?"

"Teen sen sillä ehdolla, että Puolaan palattuani saan takaisin


evankelisen pappini."

"Mutta rajakreivi, mitä hän on sanova?"

"Luultavasti jättää hän kosintansa sikseen, jollei, ei häntä koske


se, mikä on tapahtunut ennen kihlausta."

"Otatko siis hänet?"

"Meidän täytyy ensin oppia toisemme tuntemaan, sittenpähän


nähdään."

Kaikesta huolimatta rajakreivi uudisti suullisesti kosintansa ja


samalla vakuutti prinsessalle täydellisen uskonnonharjoituksen
vapauden. Kaikissa lausunnoissaan ja koko esiintymisessään
osoittautui hän sivistyneeksi, valistuneeksi mieheksi. Anna tunsi
häntä kohtaan kunnioitusta, melkeinpä ihailuakin. Sellaisen miehen
kosintaan ei saattanut vastata suorastaan hylkäävästi, ja niin ehdotti
hän vuoden ajatusaikaa, jonka jälkeen he tekisivät päätöksensä.
Rajakreivi vastasi, että vaikkei hän katsonut tarvitsevansa mitään
ajatusaikaa, tahtoi hän kuitenkin taipua prinsessan tahtoon, ja sen
jälkeen he erosivat toisistaan.

Samana päivänä kuiskailtiin hovissa miehestä mieheen, että


prinsessa oli kihloissa, että hän oli luvannut kääntyä katoliseen
uskoon, ja että rajakreivi oli matkustanut kotiin valmistamaan
morsiamensa arvokasta vastaanottoa.

Seuraavana aamuna varhain tuotiin prinsessalle kirje, ja tuoja


odotti vastausta. Kirje oli Kustaa Brahelta, joka pyysi yksityistä
keskustelua niin pian kuin mahdollista.

"Tiesin sen", tuumi Anna pamppailevin sydämin. "Nyt hänen täytyy


tulla!"

Hän määräsi kohtauksen kymmenen ajaksi omissa huoneissaan.


Kustaa herra tuli, mutta ei tyynenä ja kylmänä kuten hän oli
odottanut, vaan kiihtyneenä, leimuavin katsein. Sellaisena ei hän
ollut nähnyt häntä koskaan. Tarjoamatta kättään viittasi hän häntä
istumaan lähelleen.

"Pyydän teidän korkeudeltanne luvan seista", sanoi hän. "Ja


pyydän anteeksi, jollen voi esiintyä niin tyynesti kuin pitäisi."

"Miksi olette tullut tänne?" kysyi Anna kummissaan. "Kenties


lykkäämme johonkin toiseen päivään…?"

"Ei, nyt tai ei koskaan! Olen jo liian kauan kärsinyt sieluntuskia,


jotka ovat olleet minut surmaamaisillaan."
"Ja tahdotteko minulta niille parannusta?"

"Sitä en ole odottanut enkä toivonut. Pyydän vain tietää, miksi


olette ryöstänyt elämäni kaiken ilon ja onnen; miksi olette riistänyt
uskoni häneen, jota rakastin enemmän kuin mitään muuta
maailmassa ja joka oli vannonut pysyvänsä minulle uskollisena. Te
ette tiedä kuinka se halveksuminen, jolla hänestä puhutaan, on
vienyt kaiken elämäniloni! Minkä arvoinen on rakkaus, joka ei
perustu kunnioitukseen, sanoi hän jo lapsena; miksi on neitsyt
pettänyt ne pyhät lupaukset, jotka silloin antoi?"

Anna oli käynyt kalmankalpeaksi, mutta hän sanoi tyynellä ja


lujalla äänellä: "Muistatteko ensimäisen lupauksen, jonka annoimme
toisillemme?"

"Lupasimme rajattomasti luottaa toisiimme."

Anna katsoi vakavasti häneen, nyt oli Kustaan vuoro luoda


silmänsä maahan.

"Tiedän kyllä", sanoi Anna, "että panettelu on tahrannut nimeäni,


mutta minä nauroin sille, koska se oli ansaitsematonta… Ei
pälkähtänyt päähänikään, että luulisitte minun rakastuvan johonkin
Potsmutschiin!"

"Anna!" huudahti nuori mies.

Anna teki torjuvan liikkeen. "Olen pysynyt lujana uskossani, sen


tähden on tahdottu alentaa naisellista arvoani; mutta en ole antanut
myöten, kärsimyksistäni en ole sanonut sanaakaan. Ymmärsin kyllä,
että panettelulla tarkoitettiin myös eroittaa meidät, mutta niin luja oli
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookball.com

You might also like