2003 prentice hall, inc. all rights reserved. 1 chapter 20 – data structures outline 20.1...

44
2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory Allocation 20.4 Linked Lists 20.5 Stacks 20.6 Queues 20.7 Trees

Post on 20-Dec-2015

217 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

1

Chapter 20 – Data Structures

Outline

20.1 Introduction20.2 Self-Referential Classes20.3 Dynamic Memory Allocation20.4 Linked Lists20.5 Stacks20.6 Queues20.7 Trees

Page 2: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

2

20.1 Introduction

• Dynamic data structures– Grow and shrink at execution time

– Several types• Linked lists

• Stacks

• Queues

• Binary trees

Page 3: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

3

20.2 Self-Referential Classes

• Self-referential class– Contains instance variable referring to object of same

classclass Node { private int data; private Node nextNode; // reference to next linked node

public Node( int data) public void setData( int data) …

public void setNext( Node next) }

• Member nextNode is a link

– nextNode “links” a Node object to another Node object

Page 4: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

4

20.2 Self-Referential Classes (cont.)

Fig 20.1 Self-referential-class objects linked together.

15 10

Page 5: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

5

20.3 Dynamic Memory Allocation

• Dynamic memory allocation– Obtain more memory at execution time to store new objects

• Declaration and class-instance creation expression

Node nodeToAdd = new Node ( 10 );

Page 6: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

6

20.4 Linked Lists

• Linked list– Linear collection of self-referential classes (nodes)– Connected by reference links– Nodes can be inserted and deleted anywhere in linked list– Last node is set to null to mark end of list

• Execution Commands1. javac –classpath .;.. EmptyListException.java

2. 將 compile 過的 EmptyListException.class copy 至 ..\com\deitel\jhtp5\ch20 資料夾底下 (zip 已事先做好 )

3. javac –classpath .;.. List.java

4. 將 compile 過的 List.class, ListNode.class, copy 至 ..\com\deitel\jhtp5\ch20 資料夾底下 (zip 已事先做好 )

5. javac –classpath .;.. ListTest.java6. java –classpath .;.. ListTest

Page 7: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

7

20.4 Linked Lists (cont.)

Fig 20.2 Linked list graphical representation.

firstNode

...H D Q

lastNode

Page 8: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

List.java

Lines 6-10

1 // Fig. 20.3: List.java2 // ListNode and List class declarations.3 package com.deitel.jhtp5.ch20;4 5 // class to represent one node in a list6 class ListNode {7 8 // package access members; List can access these directly9 Object data; 10 ListNode nextNode;11 12 // create a ListNode that refers to object 13 ListNode( Object object ) 14 { 15 this( object, null ); 16 }17 18 // create ListNode that refers to Object and to next ListNode19 ListNode( Object object, ListNode node )20 {21 data = object; 22 nextNode = node; 23 }24 25 // return reference to data in node26 Object getObject() 27 { 28 return data; // return Object in this node29 }30

Self-referential class ListNode contains data

and link to nextNode

Page 9: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

List.java

Line 41

Line 42

Line 55

31 // return reference to next node in list32 ListNode getNext() 33 { 34 return nextNode; // get next node35 }36 37 } // end class ListNode38 39 // class List declaration40 public class List {41 private ListNode firstNode;42 private ListNode lastNode;43 private String name; // string like "list" used in printing44 45 // construct empty List with "list" as the name46 public List() 47 { 48 this( "list" ); 49 } 50 51 // construct an empty List with a name52 public List( String listName )53 {54 name = listName;55 firstNode = lastNode = null;56 }57 58 // insert Object at front of List59 public synchronized void insertAtFront( Object insertItem )60 {

Reference to first node in linked list

Reference to last node in linked list

First and last nodes in empty list are null

Page 10: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

List.java

Lines 61-62

Line 65

Lines 71-72

Line 74

Lines 81-82

61 if ( isEmpty() ) // firstNode and lastNode refer to same object62 firstNode = lastNode = new ListNode( insertItem );63 64 else // firstNode refers to new node65 firstNode = new ListNode( insertItem, firstNode );66 }67 68 // insert Object at end of List69 public synchronized void insertAtBack( Object insertItem )70 {71 if ( isEmpty() ) // firstNode and lastNode refer to same Object72 firstNode = lastNode = new ListNode( insertItem );73 74 else // lastNode's nextNode refers to new node75 lastNode = lastNode.nextNode = new ListNode( insertItem );76 }77 78 // remove first node from List79 public synchronized Object removeFromFront() throws EmptyListException80 {81 if ( isEmpty() ) // throw exception if List is empty82 throw new EmptyListException( name );83 84 Object removedItem = firstNode.data; // retrieve data being removed85 86 // update references firstNode and lastNode 87 if ( firstNode == lastNode )88 firstNode = lastNode = null;89 else90 firstNode = firstNode.nextNode;

If list is not empty, the first node should refer to the

newly inserted node

If list is empty, the first and last node should refer to the

newly inserted node

If list is not empty, the last node should refer to the

newly inserted node

If list is empty, removing a node causes an exception

If list is empty, the first and last node should refer to the

newly inserted node

Page 11: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

List.java

Line 100

Lines 112-117

91 92 return removedItem; // return removed node data93 94 } // end method removeFromFront95 96 // remove last node from List97 public synchronized Object removeFromBack() throws EmptyListException98 {99 if ( isEmpty() ) // throw exception if List is empty100 throw new EmptyListException( name );101 102 Object removedItem = lastNode.data; // retrieve data being removed103 104 // update references firstNode and lastNode105 if ( firstNode == lastNode )106 firstNode = lastNode = null;107 108 else { // locate new last node109 ListNode current = firstNode;110 111 // loop while current node does not refer to lastNode112 while ( current.nextNode != lastNode )113 current = current.nextNode;114 115 lastNode = current; // current is new lastNode116 current.nextNode = null;117 }118 119 return removedItem; // return removed node data120 121 } // end method removeFromBack

If list is not empty, the second-to-last node becomes the last node

If list is empty, removing a node causes an exception

Page 12: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

List.java

Lines 141-144

122 123 // determine whether list is empty124 public synchronized boolean isEmpty()125 { 126 return firstNode == null; // return true if List is empty127 }128 129 // output List contents130 public synchronized void print()131 {132 if ( isEmpty() ) {133 System.out.println( "Empty " + name );134 return;135 }136 137 System.out.print( "The " + name + " is: " );138 ListNode current = firstNode;139 140 // while not at end of list, output current node's data141 while ( current != null ) {142 System.out.print( current.data.toString() + " " );143 current = current.nextNode;144 }145 146 System.out.println( "\n" );147 }148 149 } // end class List

Traverse list and print node values

Page 13: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

EmptyListException.java

Lines 5-19

1 // Fig. 20.4: EmptyListException.java2 // Class EmptyListException declaration.3 package com.deitel.jhtp5.ch20;4 5 public class EmptyListException extends RuntimeException {6 7 // no-argument constructor8 public EmptyListException()9 {10 this( "List" ); // call other EmptyListException constructor11 }12 13 // constructor14 public EmptyListException( String name )15 {16 super( name + " is empty" ); // call superclass constructor17 }18 19 } // end class EmptyListException

Exception thrown when program attempts to remove

node from empty list

Page 14: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

ListTest.java

Line 10

Lines 13-16

Lines 19-26

1 // Fig. 20.5: ListTest.java2 // ListTest class to demonstrate List capabilities.3 import com.deitel.jhtp5.ch20.List;4 import com.deitel.jhtp5.ch20.EmptyListException;5 6 public class ListTest {7 8 public static void main( String args[] )9 {10 List list = new List(); // create the List container11 12 // objects to store in list13 Boolean bool = Boolean.TRUE;14 Character character = new Character( '$' );15 Integer integer = new Integer( 34567 );16 String string = "hello";17 18 // insert references to objects in list19 list.insertAtFront( bool ); 20 list.print(); 21 list.insertAtFront( character );22 list.print(); 23 list.insertAtBack( integer ); 24 list.print(); 25 list.insertAtBack( string ); 26 list.print(); 27

Create linked list

Create values (Objects) to store in linked-list nodes

Insert values in linked list

Page 15: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

ListTest.java

Lines 30-44

28 // remove objects from list; print after each removal29 try { 30 Object removedObject = list.removeFromFront();31 System.out.println( removedObject.toString() + " removed" );32 list.print();33 34 removedObject = list.removeFromFront();35 System.out.println( removedObject.toString() + " removed" );36 list.print();37 38 removedObject = list.removeFromBack();39 System.out.println( removedObject.toString() + " removed" );40 list.print();41 42 removedObject = list.removeFromBack();43 System.out.println( removedObject.toString() + " removed" );44 list.print();45 46 } // end try block47 48 // catch exception if remove is attempted on an empty List 49 catch ( EmptyListException emptyListException ) {50 emptyListException.printStackTrace();51 }52 }53 54 } // end class ListTest

Remove values from linked list

Page 16: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

ListTest.java

Program Output

The list is: true The list is: $ true The list is: $ true 34567 The list is: $ true 34567 hello

$ removed The list is: true 34567 hello true removedThe list is: 34567 hello hello removedThe list is: 34567 34567 removedEmpty list

Page 17: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

17

20.4 Linked Lists (cont.)

Fig 20.6 Graphical representation of operation insertAtFront.

firstNode

7 11

12

7 11

12

new Listnode

firstNode

new Listnode

(a)

(b)

Page 18: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

18

20.4 Linked Lists (cont.)

Fig 20.7 Graphical representation of operation insertAtBack.

firstNode

12

new Listnode(a)

(b) firstNode new Listnode

lastNode

lastNode

7 11 5

12 7 11 5

Page 19: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

19

20.4 Linked Lists (cont.)

Fig 20.8 Graphical representation of operation removeFromFront.

firstNode

12

(a)

(b)

7 11 5

12 7 11 5

lastNode

lastNode

firstNode

removeItem

Page 20: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

20

20.4 Linked Lists (cont.)

Fig 20.9 Graphical representation of operation removeFromBack.

12

(a)

(b)

lastNode

7 11 5

12 7 11 5

lastNode

firstNode

removeItem

firstNode current

Page 21: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

21

20.5 Stacks

• Stack– Constrained version of a linked list

• Add and remove nodes only to and from the top of the stack

– Push method adds node to top of stack

– Pop method removes node from top of stack

• Execution Commands (fig20_10)1. javac –classpath .;.. StackInheritance.java

2. 將 compile 過的 StackInheritance.class copy 至 ..\com\deitel\jhtp5\ch20 資料夾底下 (zip 已事先做好 )

3. javac –classpath .;.. StackInheritanceTest.java4. java –classpath .;.. StackInheritanceTest

Page 22: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

StackInheritance.java

Line 5

Lines 14-17

Lines 20-23

1 // Fig. 20.10: StackInheritance.java2 // Derived from class List.3 package com.deitel.jhtp5.ch20;4 5 public class StackInheritance extends List {6 7 // construct stack8 public StackInheritance() 9 { 10 super( "stack" ); 11 }12 13 // add object to stack14 public synchronized void push( Object object )15 { 16 insertAtFront( object );17 }18 19 // remove object from stack20 public synchronized Object pop() throws EmptyListException21 { 22 return removeFromFront();23 }24 25 } // end class StackInheritance

StackInheritance extends List, because a stack is a

constrained version of a linked list

Method push adds node to top of stack

Method pop removes node from top of stack

Page 23: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

StackInheritanceTest.java

Line 10

Lines 13-16

Lines 19-26

1 // Fig. 20.11: StackInheritanceTest.java2 // Class StackInheritanceTest.3 import com.deitel.jhtp5.ch20.StackInheritance;4 import com.deitel.jhtp5.ch20.EmptyListException;5 6 public class StackInheritanceTest {7 8 public static void main( String args[] )9 {10 StackInheritance stack = new StackInheritance();11 12 // create objects to store in the stack13 Boolean bool = Boolean.TRUE;14 Character character = new Character( '$' );15 Integer integer = new Integer( 34567 );16 String string = "hello";17 18 // use push method19 stack.push( bool ); 20 stack.print(); 21 stack.push( character );22 stack.print(); 23 stack.push( integer ); 24 stack.print(); 25 stack.push( string ); 26 stack.print();

Create stack

Create values (Objects) to store in stack

Insert values in stack

Page 24: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

StackInheritanceTest.java

Line 33

27 28 // remove items from stack29 try {30 Object removedObject = null;31 32 while ( true ) {33 removedObject = stack.pop(); // use pop method34 System.out.println( removedObject.toString() + " popped" );35 stack.print();36 }37 }38 39 // catch exception if stack is empty when item popped40 catch ( EmptyListException emptyListException ) {41 emptyListException.printStackTrace();42 }43 }44 45 } // end class StackInheritanceTest

Remove object from stack

Page 25: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

StackInheritanceTest.java

Program Output

The stack is: true The stack is: $ true The stack is: 34567 $ true The stack is: hello 34567 $ true hello poppedThe stack is: 34567 $ true 34567 poppedThe stack is: $ true $ poppedThe stack is: true true poppedEmpty stack

com.deitel.jhtp5.ch20.EmptyListException: stack is empty at com.deitel.jhtp5.ch20.List.removeFromFront(List.java:82) at com.deitel.jhtp5.ch20.StackInheritance.pop( StackInheritance.java:22) at StackInheritanceTest.main(StackInheritanceTest.java:33)

Page 26: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

StackComposition.java

Lines 15-18

Lines 21-24

1 // Fig. 20.12: StackComposition.java2 // Class StackComposition declaration with composed List object.3 package com.deitel.jhtp5.ch20;4 5 public class StackComposition {6 private List stackList;7 8 // construct stack9 public StackComposition() 10 { 11 stackList = new List( "stack" );12 }13 14 // add object to stack15 public synchronized void push( Object object )16 { 17 stackList.insertAtFront( object );18 }19 20 // remove object from stack21 public synchronized Object pop() throws EmptyListException22 { 23 return stackList.removeFromFront();24 }25

Method push adds node to top of stack

Method pop removes node from top of stack

Page 27: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

StackComposition.java

26 // determine if stack is empty27 public synchronized boolean isEmpty()28 { 29 return stackList.isEmpty();30 }31 32 // output stack contents33 public synchronized void print()34 { 35 stackList.print();36 }37 38 } // end class StackComposition

Page 28: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

28

20.6 Queues

• Queue– Similar to a supermarket checkout line

– Nodes inserted only at tail (back)• Method enqueue

– Nodes removed only from head (front)• Method dequeue

Page 29: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

Queue.java

Lines 15-18

Lines 21-24

1 // Fig. 20.13: Queue.java2 // Class Queue.3 package com.deitel.jhtp5.ch20;4 5 public class Queue {6 private List queueList;7 8 // construct queue9 public Queue() 10 { 11 queueList = new List( "queue" );12 }13 14 // add object to queue15 public synchronized void enqueue( Object object )16 { 17 queueList.insertAtBack( object );18 }19 20 // remove object from queue21 public synchronized Object dequeue() throws EmptyListException22 { 23 return queueList.removeFromFront();24 }25

Method enqueue adds node to top of stack

Method dequeue removes node from

top of stack

Page 30: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

Queue.java

26 // determine if queue is empty27 public synchronized boolean isEmpty()28 {29 return queueList.isEmpty();30 }31

32 // output queue contents33 public synchronized void print()34 {35 queueList.print();36 }37

38 } // end class Queue

Page 31: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

QueueTest.java

Line 10

Lines 13-16

Lines 19-26

1 // Fig. 20.14: QueueTest.java2 // Class QueueTest.3 import com.deitel.jhtp5.ch20.Queue;4 import com.deitel.jhtp5.ch20.EmptyListException;5 6 public class QueueTest {7 8 public static void main( String args[] )9 {10 Queue queue = new Queue();11 12 // create objects to store in queue13 Boolean bool = Boolean.TRUE;14 Character character = new Character( '$' );15 Integer integer = new Integer( 34567 );16 String string = "hello";17 18 // use enqueue method19 queue.enqueue( bool ); 20 queue.print(); 21 queue.enqueue( character );22 queue.print(); 23 queue.enqueue( integer ); 24 queue.print(); 25 queue.enqueue( string ); 26 queue.print();

Create queue

Create values (Objects) to store in queue

Insert values in queue

Page 32: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

QueueTest.java

Line 33

27 28 // remove objects from queue29 try {30 Object removedObject = null;31 32 while ( true ) {33 removedObject = queue.dequeue(); // use dequeue method34 System.out.println( removedObject.toString() + " dequeued" );35 queue.print();36 }37 }38 39 // process exception if queue is empty when item removed40 catch ( EmptyListException emptyListException ) {41 emptyListException.printStackTrace();42 }43 }44 45 } // end class QueueCompositionTest

Remove value from queue

Page 33: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

QueueTest.java

The queue is: true

 

The queue is: true $

 

The queue is: true $ 34567

 

The queue is: true $ 34567 hello

 

true dequeued

The queue is: $ 34567 hello

$ dequeued

The queue is: 34567 hello

 

34567 dequeued

The queue is: hello

 

hello dequeued

Empty queue

com.deitel.jhtp5.ch20.EmptyListException: queue is empty

at com.deitel.jhtp5.ch20.List.removeFromFront(List.java:88)

at com.deitel.jhtp5.ch20.Queue.dequeue(Queue.java:23)

at QueueTest.main(QueueTest.java:33)

Page 34: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

34

20.7 Trees

• Tree– Non-linear, two-dimensional data structure

• (unlike linked lists, stacks and queues)

– Nodes contain two or more links

– Root node is the first node

– Each link refers to a child• Left child is the first node in left subtree

• Right child is the first node in right subtree

• Children of a specific node are siblings

• Nodes with no children are leaf nodes

Page 35: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

35

20.7 Trees (cont.)

• Binary search tree– Special ordering of nodes

• Values in left subtrees are less than values in right subtrees

– Inorder traversal• Traverse left subtree, obtain node value, traverse right subtree

– Preorder traversal• Obtain node value, traverse left subtree, traverse right subtree

– Postorder traversal• Traverse left subtree, traverse right subtree, obtain node value

Page 36: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

36

20.7 Trees (cont.)

Fig 20.15 Binary tree graphical representation.

B

A D

C

Page 37: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

37

20.7 Trees (cont.)

Fig 20.16 Binary search tree containing 12 values.

47

11 43 65 93

25 77

7 17 31 44 68

Page 38: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

Tree.java

Lines 9 and 11

Lines 24-32

1 // Fig. 20.17: Tree.java2 // Declaration of class TreeNode and class Tree.3 package com.deitel.jhtp5.ch20;4 5 // class TreeNode declaration6 class TreeNode {7 8 // package access members9 TreeNode leftNode; 10 int data; 11 TreeNode rightNode; 12 13 // initialize data and make this a leaf node14 public TreeNode( int nodeData )15 { 16 data = nodeData; 17 leftNode = rightNode = null; // node has no children18 }19 20 // locate insertion point and insert new node; ignore duplicate values21 public synchronized void insert( int insertValue )22 {23 // insert in left subtree24 if ( insertValue < data ) {25 26 // insert new TreeNode27 if ( leftNode == null )28 leftNode = new TreeNode( insertValue );29

Left and right children

If value of inserted node is less than value

of tree node, insert node in left subtree

Page 39: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

Tree.java

Lines 35-43

30 else // continue traversing left subtree31 leftNode.insert( insertValue ); 32 }33 34 // insert in right subtree35 else if ( insertValue > data ) {36 37 // insert new TreeNode38 if ( rightNode == null )39 rightNode = new TreeNode( insertValue );40 41 else // continue traversing right subtree42 rightNode.insert( insertValue ); 43 }44 45 } // end method insert46 47 } // end class TreeNode48 49 // class Tree declaration50 public class Tree {51 private TreeNode root;52 53 // construct an empty Tree of integers54 public Tree() 55 { 56 root = null; 57 }58 59 // insert a new node in the binary search tree60 public synchronized void insertNode( int insertValue )61 {

If value of inserted node is greater than value of tree node, insert node in right

subtree

Page 40: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

Tree.java

Lines 81-93

62 if ( root == null )63 root = new TreeNode( insertValue ); // create the root node here64 65 else66 root.insert( insertValue ); // call the insert method67 }68 69 // begin preorder traversal70 public synchronized void preorderTraversal()71 { 72 preorderHelper( root ); 73 }74 75 // recursive method to perform preorder traversal76 private void preorderHelper( TreeNode node )77 {78 if ( node == null )79 return;80 81 System.out.print( node.data + " " ); // output node data82 preorderHelper( node.leftNode ); // traverse left subtree 83 preorderHelper( node.rightNode ); // traverse right subtree84 }85 86 // begin inorder traversal87 public synchronized void inorderTraversal()88 { 89 inorderHelper( root ); 90 }91

Preorder traversal – obtain data, traverse left subtree, then traverse right subtree

Page 41: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

Tree.java

Lines 98-100

Lines 115-117

92 // recursive method to perform inorder traversal93 private void inorderHelper( TreeNode node )94 {95 if ( node == null )96 return;97 98 inorderHelper( node.leftNode ); // traverse left subtree99 System.out.print( node.data + " " ); // output node data100 inorderHelper( node.rightNode ); // traverse right subtree101 }102 103 // begin postorder traversal104 public synchronized void postorderTraversal()105 { 106 postorderHelper( root ); 107 }108 109 // recursive method to perform postorder traversal110 private void postorderHelper( TreeNode node )111 {112 if ( node == null )113 return;114 115 postorderHelper( node.leftNode ); // traverse left subtree 116 postorderHelper( node.rightNode ); // traverse right subtree117 System.out.print( node.data + " " ); // output node data118 }119 120 } // end class Tree

Inorder traversal – traverse left subtree, obtain data, then

traverse right subtree

Postorder traversal – traverse left subtree, traverse right subtree, then obtain data

Page 42: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

TreeTest.java

Lines 15-19

Line 22

Line 25

1 // Fig. 20.18: TreeTest.java2 // This program tests class Tree.3 import com.deitel.jhtp5.ch20.Tree;4 5 public class TreeTest {6 7 public static void main( String args[] )8 {9 Tree tree = new Tree();10 int value;11 12 System.out.println( "Inserting the following values: " );13 14 // insert 10 random integers from 0-99 in tree 15 for ( int i = 1; i <= 10; i++ ) {16 value = ( int ) ( Math.random() * 100 );17 System.out.print( value + " " );18 tree.insertNode( value );19 }20 21 System.out.println ( "\n\nPreorder traversal" );22 tree.preorderTraversal(); // perform preorder traversal of tree23 24 System.out.println ( "\n\nInorder traversal" );25 tree.inorderTraversal(); // perform inorder traversal of tree

Insert 10 random integers in tree

Traverse binary tree via preorder algorithm

Traverse binary tree via inorder algorithm

Page 43: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc.All rights reserved.

Outline

TreeTest.java

Line 28

26 27 System.out.println ( "\n\nPostorder traversal" );28 tree.postorderTraversal(); // perform postorder traversal of tree29 System.out.println();30 }31 32 } // end class TreeTest

Inserting the following values: 39 69 94 47 50 72 55 41 97 73  Preorder traversal39 69 47 41 50 55 94 72 73 97  Inorder traversal39 41 47 50 55 69 72 73 94 97  Postorder traversal41 55 50 47 73 72 97 94 69 39

Traverse binary tree via postorder algorithm

Page 44: 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory

2003 Prentice Hall, Inc. All rights reserved.

44

20.7 Trees (cont.)

Fig 20.19 Binary search tree with seven values.

27

6 17 33 48

13 42