• No results found

Chapter 20 – Data Structures

N/A
N/A
Protected

Academic year: 2021

Share "Chapter 20 – Data Structures"

Copied!
44
0
0

Loading.... (view fulltext now)

Full text

(1)

Chapter 20 – Data Structures

1

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

(2)

2

20.1 Introduction

• Dynamic data structures

– Grow and shrink at execution time – Several types

• Linked lists

• Stacks

• Queues

• Binary trees

(3)

3

20.2 Self-Referential Classes

• Self-referential class

– Contains instance variable referring to object of same class

class Node {

private int data;

private Node nextNode; // reference to next linked node }

• Member nextNode is a link

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

(4)

4

20.2 Self-Referential Classes (cont.)

Fig 20.1 Self-referential-class objects linked together.

15 10

(5)

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

(6)

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

(7)

7

20.4 Linked Lists (cont.)

Fig 20.2 Linked list graphical representation.

firstNode

H D ... Q

lastNode

(8)

Outline

List.java Lines 6-10

1 // Fig. 20.3: List.java

2 // ListNode and List class declarations.

3 package com.deitel.jhtp5.ch20;

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 // 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 ListNode 19 ListNode( Object object, ListNode node )

20 {

21 data = object;

22 nextNode = node;

23 } 24

25 // return reference to data in node 26 Object getObject()

27 {

28 return data; // return Object in this node 29 }

Self-referential class ListNode contains data

and link to nextNode

(9)

2003 Prentice Hall, Inc.

Outline

List.java Line 41

Line 42 Line 55

31 // return reference to next node in list 32 ListNode getNext()

33 {

34 return nextNode; // get next node 35 }

36

37 } // end class ListNode 38

39 // class List declaration 40 public class List {

41 private ListNode firstNode;

42 private ListNode lastNode;

43 private String name; // string like "list" used in printing 44

45 // construct empty List with "list" as the name 46 public List()

47 {

48 this( "list" );

49 } 50

51 // construct an empty List with a name 52 public List( String listName )

53 {

54 name = listName;

55 firstNode = lastNode = null;

56 } 57

58 // insert Object at front of List

59 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

(10)

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 object 62 firstNode = lastNode = new ListNode( insertItem );

63

64 else // firstNode refers to new node

65 firstNode = new ListNode( insertItem, firstNode );

66 } 67

68 // insert Object at end of List

69 public synchronized void insertAtBack( Object insertItem ) 70 {

71 if ( isEmpty() ) // firstNode and lastNode refer to same Object 72 firstNode = lastNode = new ListNode( insertItem );

73

74 else // lastNode's nextNode refers to new node

75 lastNode = lastNode.nextNode = new ListNode( insertItem );

76 } 77

78 // remove first node from List

79 public synchronized Object removeFromFront() throws EmptyListException 80 {

81 if ( isEmpty() ) // throw exception if List is empty 82 throw new EmptyListException( name );

83

84 Object removedItem = firstNode.data; // retrieve data being removed 85

86 // update references firstNode and lastNode 87 if ( firstNode == lastNode )

88 firstNode = lastNode = null;

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

(11)

2003 Prentice Hall, Inc.

Outline

List.java Line 100

Lines 112-117

91

92 return removedItem; // return removed node data 93

94 } // end method removeFromFront 95

96 // remove last node from List

97 public synchronized Object removeFromBack() throws EmptyListException 98 {

99 if ( isEmpty() ) // throw exception if List is empty 100 throw new EmptyListException( name );

101

102 Object removedItem = lastNode.data; // retrieve data being removed 103

104 // update references firstNode and lastNode 105 if ( firstNode == lastNode )

106 firstNode = lastNode = null;

107

108 else { // locate new last node 109 ListNode current = firstNode;

110

111 // loop while current node does not refer to lastNode 112 while ( current.nextNode != lastNode )

113 current = current.nextNode;

114

115 lastNode = current; // current is new lastNode 116 current.nextNode = null;

117 } 118

119 return removedItem; // return removed node data 120

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

(12)

Outline

List.java Lines 141-144

122

123 // determine whether list is empty 124 public synchronized boolean isEmpty() 125 {

126 return firstNode == null; // return true if List is empty 127 }

128

129 // output List contents

130 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 data 141 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

(13)

2003 Prentice Hall, Inc.

Outline

EmptyListExcept ion.java

Lines 5-19

1 // Fig. 20.4: EmptyListException.java 2 // Class EmptyListException declaration.

3 package com.deitel.jhtp5.ch20;

4

5 public class EmptyListException extends RuntimeException { 6

7 // no-argument constructor 8 public EmptyListException() 9 {

10 this( "List" ); // call other EmptyListException constructor 11 }

12

13 // constructor

14 public EmptyListException( String name ) 15 {

16 super( name + " is empty" ); // call superclass constructor 17 }

18

19 } // end class EmptyListException

Exception thrown when program attempts to remove

node from empty list

(14)

Outline

ListTest.java Line 10

Lines 13-16 Lines 19-26

1 // Fig. 20.5: ListTest.java

2 // 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 container 11

12 // objects to store in list 13 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 list 19 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

(15)

2003 Prentice Hall, Inc.

Outline

ListTest.java Lines 30-44

28 // remove objects from list; print after each removal 29 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 block 47

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

(16)

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 removed

The list is: 34567 hello  

hello removed The list is: 34567  

34567 removed Empty list

(17)

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)

(18)

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

(19)

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

(20)

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

(21)

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

(22)

Outline

StackInheritanc e.java

Line 5

Lines 14-17 Lines 20-23

1 // Fig. 20.10: StackInheritance.java 2 // Derived from class List.

3 package com.deitel.jhtp5.ch20;

4

5 public class StackInheritance extends List { 6

7 // construct stack

8 public StackInheritance() 9 {

10 super( "stack" );

11 } 12

13 // add object to stack

14 public synchronized void push( Object object ) 15 {

16 insertAtFront( object );

17 } 18

19 // remove object from stack

20 public synchronized Object pop() throws EmptyListException 21 {

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

(23)

2003 Prentice Hall, Inc.

Outline

StackInheritanc eTest.java

Line 10 Lines 13-16 Lines 19-26

1 // Fig. 20.11: StackInheritanceTest.java 2 // 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 stack 13 Boolean bool = Boolean.TRUE;

14 Character character = new Character( '$' );

15 Integer integer = new Integer( 34567 );

16 String string = "hello";

17

18 // use push method

19 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

(24)

Outline

StackInheritanc eTest.java

Line 33

27

28 // remove items from stack 29 try {

30 Object removedObject = null;

31

32 while ( true ) {

33 removedObject = stack.pop(); // use pop method

34 System.out.println( removedObject.toString() + " popped" );

35 stack.print();

36 } 37 } 38

39 // catch exception if stack is empty when item popped 40 catch ( EmptyListException emptyListException ) { 41 emptyListException.printStackTrace();

42 } 43 } 44

45 } // end class StackInheritanceTest

Remove object from stack

(25)

2003 Prentice Hall, Inc.

Outline

StackInheritanc eTest.java

Program Output

The stack is: true The stack is: $ true

The stack is: 34567 $ true

The stack is: hello 34567 $ true hello popped

The stack is: 34567 $ true 34567 popped

The stack is: $ true

$ popped

The stack is: true true popped

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

(26)

Outline

StackCompositio n.java

Lines 15-18 Lines 21-24

1 // Fig. 20.12: StackComposition.java

2 // 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 stack

9 public StackComposition() 10 {

11 stackList = new List( "stack" );

12 } 13

14 // add object to stack

15 public synchronized void push( Object object ) 16 {

17 stackList.insertAtFront( object );

18 } 19

20 // remove object from stack

21 public synchronized Object pop() throws EmptyListException 22 {

23 return stackList.removeFromFront();

24 } 25

Method push adds node to top of stack

Method pop removes node from top of stack

(27)

2003 Prentice Hall, Inc.

Outline

StackCompositio n.java

26 // determine if stack is empty

27 public synchronized boolean isEmpty() 28 {

29 return stackList.isEmpty();

30 } 31

32 // output stack contents

33 public synchronized void print() 34 {

35 stackList.print();

36 } 37

38 } // end class StackComposition

(28)

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

(29)

2003 Prentice Hall, Inc.

Outline

Queue.java Lines 15-18 Lines 21-24

1 // Fig. 20.13: Queue.java 2 // Class Queue.

3 package com.deitel.jhtp5.ch20;

4

5 public class Queue {

6 private List queueList;

7

8 // construct queue 9 public Queue() 10 {

11 queueList = new List( "queue" );

12 } 13

14 // add object to queue

15 public synchronized void enqueue( Object object ) 16 {

17 queueList.insertAtBack( object );

18 } 19

20 // remove object from queue

21 public synchronized Object dequeue() throws EmptyListException 22 {

23 return queueList.removeFromFront();

24 } 25

Method enqueue adds node to top of stack

Method dequeue removes node from

top of stack

(30)

Outline

Queue.java

26 // determine if queue is empty

27 public synchronized boolean isEmpty() 28 {

29 return queueList.isEmpty();

30 } 31

32 // output queue contents

33 public synchronized void print() 34 {

35 queueList.print();

36 } 37

38 } // end class Queue

(31)

2003 Prentice Hall, Inc.

Outline

QueueTest.java Line 10

Lines 13-16 Lines 19-26

1 // Fig. 20.14: QueueTest.java 2 // 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 queue 13 Boolean bool = Boolean.TRUE;

14 Character character = new Character( '$' );

15 Integer integer = new Integer( 34567 );

16 String string = "hello";

17

18 // use enqueue method

19 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

(32)

Outline

QueueTest.java Line 33

27

28 // remove objects from queue 29 try {

30 Object removedObject = null;

31

32 while ( true ) {

33 removedObject = queue.dequeue(); // use dequeue method

34 System.out.println( removedObject.toString() + " dequeued" );

35 queue.print();

36 } 37 } 38

39 // process exception if queue is empty when item removed 40 catch ( EmptyListException emptyListException ) {

41 emptyListException.printStackTrace();

42 } 43 } 44

45 } // end class QueueCompositionTest

Remove value from queue

(33)

2003 Prentice Hall, Inc.

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)

(34)

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

(35)

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

(36)

36

20.7 Trees (cont.)

Fig 20.15 Binary tree graphical representation.

B

A D

C

(37)

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

(38)

Outline

Tree.java Lines 9 and 11 Lines 24-32

1 // Fig. 20.17: Tree.java

2 // Declaration of class TreeNode and class Tree.

3 package com.deitel.jhtp5.ch20;

4

5 // class TreeNode declaration 6 class TreeNode {

7

8 // package access members 9 TreeNode leftNode;

10 int data;

11 TreeNode rightNode;

12

13 // initialize data and make this a leaf node 14 public TreeNode( int nodeData )

15 {

16 data = nodeData;

17 leftNode = rightNode = null; // node has no children 18 }

19

20 // locate insertion point and insert new node; ignore duplicate values 21 public synchronized 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 );

Left and right children

If value of inserted node is less than value

of tree node, insert node in left subtree

(39)

2003 Prentice Hall, Inc.

Outline

Tree.java Lines 35-43

30 else // continue traversing left subtree 31 leftNode.insert( insertValue );

32 } 33

34 // insert in right subtree

35 else if ( insertValue > data ) { 36

37 // insert new TreeNode 38 if ( rightNode == null )

39 rightNode = new TreeNode( insertValue );

40

41 else // continue traversing right subtree 42 rightNode.insert( insertValue );

43 } 44

45 } // end method insert 46

47 } // end class TreeNode 48

49 // class Tree declaration 50 public class Tree {

51 private TreeNode root;

52

53 // construct an empty Tree of integers 54 public Tree()

55 {

56 root = null;

57 } 58

59 // insert a new node in the binary search tree

60 public synchronized void insertNode( int insertValue ) 61 {

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

subtree

(40)

Outline

Tree.java Lines 81-93

62 if ( root == null )

63 root = new TreeNode( insertValue ); // create the root node here 64

65 else

66 root.insert( insertValue ); // call the insert method 67 }

68

69 // begin preorder traversal

70 public synchronized void preorderTraversal() 71 {

72 preorderHelper( root );

73 } 74

75 // recursive method to perform preorder traversal 76 private void preorderHelper( TreeNode node ) 77 {

78 if ( node == null ) 79 return;

80

81 System.out.print( node.data + " " ); // output node data

82 preorderHelper( node.leftNode ); // traverse left subtree 83 preorderHelper( node.rightNode ); // traverse right subtree 84 }

85

86 // begin inorder traversal

87 public synchronized void inorderTraversal() 88 {

89 inorderHelper( root );

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

(41)

2003 Prentice Hall, Inc.

Outline

Tree.java Lines 98-100 Lines 115-117

92 // recursive method to perform inorder traversal 93 private void inorderHelper( TreeNode node ) 94 {

95 if ( node == null ) 96 return;

97

98 inorderHelper( node.leftNode ); // traverse left subtree 99 System.out.print( node.data + " " ); // output node data

100 inorderHelper( node.rightNode ); // traverse right subtree 101 }

102

103 // begin postorder traversal

104 public synchronized void postorderTraversal() 105 {

106 postorderHelper( root );

107 } 108

109 // recursive method to perform postorder traversal 110 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 subtree 117 System.out.print( node.data + " " ); // output node data

118 } 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

(42)

Outline

TreeTest.java Lines 15-19

Line 22 Line 25

1 // Fig. 20.18: TreeTest.java 2 // 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 tree 23

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

(43)

2003 Prentice Hall, Inc.

Outline

TreeTest.java Line 28

26

27 System.out.println ( "\n\nPostorder traversal" );

28 tree.postorderTraversal(); // perform postorder traversal of tree 29 System.out.println();

30 } 31

32 } // end class TreeTest Inserting the following values:

39 69 94 47 50 72 55 41 97 73 Preorder traversal

39 69 47 41 50 55 94 72 73 97 Inorder traversal

39 41 47 50 55 69 72 73 94 97 Postorder traversal

41 55 50 47 73 72 97 94 69 39

Traverse binary tree via postorder algorithm

(44)

44

20.7 Trees (cont.)

Fig 20.19 Binary search tree with seven values.

27

6 17 33 48

13 42

References

Related documents

Specialization: Digital design(System design,RTL and Verification), Verilog Main business: Design, Research, Offshore projects. Description: ARF-Design works in two domains of

mitted into metal through a gas cut surface. Shearing, cropping and gas cutting, shall be clean, reasonably square, and free from any distortions, and should the

A doubly linked list is like a linked list, but each node also has a previous field, which points to the nodes predecessor..

Therefore dynamic SCPC delivers the same dynamic bandwidth allocation functionality of the iDirect Shared Service, while dramatically reducing required return link

The active nodes mean that the sensor node has enough energy to transfer data to other nodes, but some sensor nodes can be deleted from the active nodes list if

The last node points to NULL Declaring a Linked list In C language a linked list would be implemented using structure and pointers struct LinkedList int data.. Creating nodes

 a linked list is a list in which the order of the components is determined by an explicit link member in each node..  the nodes are struct s--each node contains a

Dalam hal ini perjanjian internasional yang menjadi objek kajian adalah Mutual Commitments antara Pemerintah Liberia dan United Nations Peacebuilding Commision dalam