SlideShare une entreprise Scribd logo
1  sur  44
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
20.1  Introduction ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
20.2  Self-Referential Classes ,[object Object],[object Object],[object Object],[object Object],[object Object]
20.2  Self-Referential Classes (cont.) Fig 20.1 Self-referential-class objects linked together. 15 10
20.3  Dynamic Memory Allocation ,[object Object],[object Object],[object Object],[object Object]
20.4  Linked Lists ,[object Object],[object Object],[object Object],[object Object],[object Object]
20.4  Linked Lists (cont.) Fig 20.2 Linked list graphical representation. firstNode ... H D Q lastNode
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  } 30  Self-referential class  ListNode  contains  data  and link to  nextNode
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
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 ; 89  else 90  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
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
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(  ""  ); 147  } 148  149  }  // end class List Traverse list and print node values
EmptyListException.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
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 ( Object s) to store in linked-list nodes Insert values in linked list
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
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
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)
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
20.4  Linked Lists (cont.) Fig 20.8 Graphical representation of operation  removeFromFront . firstNode 12 (a) (b) 7 11 5 lastNode lastNode firstNode removeItem 12 7 11 5
20.4  Linked Lists (cont.) Fig 20.9 Graphical representation of operation  removeFromBack . 12 (a) (b) lastNode 7 11 5 lastNode firstNode removeItem firstNode current 12 7 11 5
20.5  Stacks ,[object Object],[object Object],[object Object],[object Object],[object Object]
StackInheritance.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
StackInheritanceTest.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 ( Object s) to store in stack Insert values in stack
StackInheritanceTest.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
StackInheritanceTest.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)
StackComposition.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
StackComposition.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
20.6  Queues ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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
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
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 ( Object s) to store in queue Insert values in queue
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
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)
20.7  Trees ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
20.7  Trees (cont.) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
20.7  Trees (cont.) Fig 20.15 Binary tree graphical representation. B A D C
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
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 ); 29  Left and right children If value of inserted node is less than value of tree node, insert node in left subtree
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
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 +  &quot; &quot;  );  // 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 );  90  } 91  Preorder traversal – obtain data, traverse left subtree, then traverse right subtree
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 +  &quot; &quot;  );  // 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 +  &quot; &quot;  );  // 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
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(  &quot;Inserting the following values: &quot;  ); 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 +  &quot; &quot;  ); 18  tree.insertNode( value ); 19  } 20  21  System.out.println (  &quot;Preorder traversal&quot;  ); 22  tree.preorderTraversal();  // perform preorder traversal of tree 23  24  System.out.println (  &quot;Inorder traversal&quot;  ); 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
TreeTest.java   Line 28 26  27  System.out.println (  &quot;Postorder traversal&quot;  ); 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
20.7  Trees (cont.) Fig 20.19 Binary search tree with seven values. 27 6 17 33 48 13 42

Contenu connexe

Tendances

Unit ii(dsc++)
Unit ii(dsc++)Unit ii(dsc++)
Unit ii(dsc++)Durga Devi
 
Data structure lecture 5
Data structure lecture 5Data structure lecture 5
Data structure lecture 5Kumar
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structureTushar Aneyrao
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory archana singh
 
Operations on linked list
Operations on linked listOperations on linked list
Operations on linked listSumathi Kv
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIjagriti srivastava
 

Tendances (19)

Unit ii(dsc++)
Unit ii(dsc++)Unit ii(dsc++)
Unit ii(dsc++)
 
Data Structure (Circular Linked List)
Data Structure (Circular Linked List)Data Structure (Circular Linked List)
Data Structure (Circular Linked List)
 
CSE240 Doubly Linked Lists
CSE240 Doubly Linked ListsCSE240 Doubly Linked Lists
CSE240 Doubly Linked Lists
 
Data structure lecture 5
Data structure lecture 5Data structure lecture 5
Data structure lecture 5
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structure
 
LINKED LISTS
LINKED LISTSLINKED LISTS
LINKED LISTS
 
Xxxx
XxxxXxxx
Xxxx
 
Linked list
Linked listLinked list
Linked list
 
Doubly linked list (animated)
Doubly linked list (animated)Doubly linked list (animated)
Doubly linked list (animated)
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
QA Auotmation Java programs,theory
QA Auotmation Java programs,theory QA Auotmation Java programs,theory
QA Auotmation Java programs,theory
 
Linked list
Linked listLinked list
Linked list
 
Linkedlist
LinkedlistLinkedlist
Linkedlist
 
Linkedlist
LinkedlistLinkedlist
Linkedlist
 
Operations on linked list
Operations on linked listOperations on linked list
Operations on linked list
 
Posfix
PosfixPosfix
Posfix
 
Perl
PerlPerl
Perl
 
Basic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time APIBasic java, java collection Framework and Date Time API
Basic java, java collection Framework and Date Time API
 

En vedette

Trabajo Practico Uap Arreglos
Trabajo Practico Uap ArreglosTrabajo Practico Uap Arreglos
Trabajo Practico Uap Arreglosmartha leon
 
Ejemplos Importantisimo
Ejemplos  ImportantisimoEjemplos  Importantisimo
Ejemplos Importantisimomartha leon
 
Arrays In General
Arrays In GeneralArrays In General
Arrays In Generalmartha leon
 
Unidad16 Codigof1
Unidad16 Codigof1Unidad16 Codigof1
Unidad16 Codigof1martha leon
 
A Healthy Life
A Healthy LifeA Healthy Life
A Healthy Lifesabina22
 

En vedette (8)

Trabajo Practico Uap Arreglos
Trabajo Practico Uap ArreglosTrabajo Practico Uap Arreglos
Trabajo Practico Uap Arreglos
 
Ejemplos Importantisimo
Ejemplos  ImportantisimoEjemplos  Importantisimo
Ejemplos Importantisimo
 
Arrays In General
Arrays In GeneralArrays In General
Arrays In General
 
3433 Ch10 Ppt
3433 Ch10 Ppt3433 Ch10 Ppt
3433 Ch10 Ppt
 
Unidad16 Codigof1
Unidad16 Codigof1Unidad16 Codigof1
Unidad16 Codigof1
 
3433 Ch09 Ppt
3433 Ch09 Ppt3433 Ch09 Ppt
3433 Ch09 Ppt
 
A Healthy Life
A Healthy LifeA Healthy Life
A Healthy Life
 
Lapomadita Renguera
Lapomadita RengueraLapomadita Renguera
Lapomadita Renguera
 

Similaire à Jhtp5 20 Datastructures

Csphtp1 23
Csphtp1 23Csphtp1 23
Csphtp1 23HUST
 
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfPROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfclimatecontrolsv
 
please i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdfplease i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdfezonesolutions
 
File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfConint29
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdfImplement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdffootstatus
 
Sorted number list implementation with linked listsStep 1 Inspec.pdf
 Sorted number list implementation with linked listsStep 1 Inspec.pdf Sorted number list implementation with linked listsStep 1 Inspec.pdf
Sorted number list implementation with linked listsStep 1 Inspec.pdfalmaniaeyewear
 
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdfClass DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdfxlynettalampleyxc
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfamazing2001
 
Lecture 18Dynamic Data Structures and Generics (II).docx
Lecture 18Dynamic Data Structures and Generics (II).docxLecture 18Dynamic Data Structures and Generics (II).docx
Lecture 18Dynamic Data Structures and Generics (II).docxSHIVA101531
 
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
 The MyLinkedList class used in Listing 24.6 is a one-way directional .docx The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
The MyLinkedList class used in Listing 24.6 is a one-way directional .docxKomlin1
 
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdfProblem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdfJamesPXNNewmanp
 
Exception to indicate that Singly LinkedList is empty. .pdf
  Exception to indicate that Singly LinkedList is empty. .pdf  Exception to indicate that Singly LinkedList is empty. .pdf
Exception to indicate that Singly LinkedList is empty. .pdfaravlitraders2012
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfInspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfvishalateen
 

Similaire à Jhtp5 20 Datastructures (20)

Csphtp1 23
Csphtp1 23Csphtp1 23
Csphtp1 23
 
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfPROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
 
please i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdfplease i need help Im writing a program to test the merge sort alg.pdf
please i need help Im writing a program to test the merge sort alg.pdf
 
File LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdfFile LinkedList.java Defines a doubly-l.pdf
File LinkedList.java Defines a doubly-l.pdf
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdfImplement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
 
Sorted number list implementation with linked listsStep 1 Inspec.pdf
 Sorted number list implementation with linked listsStep 1 Inspec.pdf Sorted number list implementation with linked listsStep 1 Inspec.pdf
Sorted number list implementation with linked listsStep 1 Inspec.pdf
 
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdfClass DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
 
Lecture 18Dynamic Data Structures and Generics (II).docx
Lecture 18Dynamic Data Structures and Generics (II).docxLecture 18Dynamic Data Structures and Generics (II).docx
Lecture 18Dynamic Data Structures and Generics (II).docx
 
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
 The MyLinkedList class used in Listing 24.6 is a one-way directional .docx The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
The MyLinkedList class used in Listing 24.6 is a one-way directional .docx
 
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdfProblem- Describe an algorithm for concatenating two singly linked lis.pdf
Problem- Describe an algorithm for concatenating two singly linked lis.pdf
 
Exception to indicate that Singly LinkedList is empty. .pdf
  Exception to indicate that Singly LinkedList is empty. .pdf  Exception to indicate that Singly LinkedList is empty. .pdf
Exception to indicate that Singly LinkedList is empty. .pdf
 
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdfInspect the class declaration for a doubly-linked list node in Node-h-.pdf
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 
Stack queue
Stack queueStack queue
Stack queue
 

Plus de martha leon

Silabo Prog De Computadoras 2
Silabo Prog  De Computadoras 2Silabo Prog  De Computadoras 2
Silabo Prog De Computadoras 2martha leon
 
Tema2 C++ 2004 2005
Tema2 C++ 2004 2005Tema2 C++ 2004 2005
Tema2 C++ 2004 2005martha leon
 
B2 T5 Vectores Ii
B2 T5 Vectores IiB2 T5 Vectores Ii
B2 T5 Vectores Iimartha leon
 
Sem5 Interaccion Con La Computadoras Software
Sem5 Interaccion Con La Computadoras   SoftwareSem5 Interaccion Con La Computadoras   Software
Sem5 Interaccion Con La Computadoras Softwaremartha leon
 
Sem2 En El Interior De Las Computadoras Hardware I
Sem2 En El Interior De Las Computadoras   Hardware ISem2 En El Interior De Las Computadoras   Hardware I
Sem2 En El Interior De Las Computadoras Hardware Imartha leon
 
Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3martha leon
 
Sem1 El Mundo De Las Computadoras
Sem1 El Mundo De Las ComputadorasSem1 El Mundo De Las Computadoras
Sem1 El Mundo De Las Computadorasmartha leon
 
Sem3 En El Interior De Las Computadoras Hardware Ii
Sem3 En El Interior De Las Computadoras   Hardware IiSem3 En El Interior De Las Computadoras   Hardware Ii
Sem3 En El Interior De Las Computadoras Hardware Iimartha leon
 

Plus de martha leon (9)

SeúDocodigo
SeúDocodigoSeúDocodigo
SeúDocodigo
 
Silabo Prog De Computadoras 2
Silabo Prog  De Computadoras 2Silabo Prog  De Computadoras 2
Silabo Prog De Computadoras 2
 
Tema2 C++ 2004 2005
Tema2 C++ 2004 2005Tema2 C++ 2004 2005
Tema2 C++ 2004 2005
 
B2 T5 Vectores Ii
B2 T5 Vectores IiB2 T5 Vectores Ii
B2 T5 Vectores Ii
 
Sem5 Interaccion Con La Computadoras Software
Sem5 Interaccion Con La Computadoras   SoftwareSem5 Interaccion Con La Computadoras   Software
Sem5 Interaccion Con La Computadoras Software
 
Sem2 En El Interior De Las Computadoras Hardware I
Sem2 En El Interior De Las Computadoras   Hardware ISem2 En El Interior De Las Computadoras   Hardware I
Sem2 En El Interior De Las Computadoras Hardware I
 
Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3Ejemplos Interfaces Usuario 3
Ejemplos Interfaces Usuario 3
 
Sem1 El Mundo De Las Computadoras
Sem1 El Mundo De Las ComputadorasSem1 El Mundo De Las Computadoras
Sem1 El Mundo De Las Computadoras
 
Sem3 En El Interior De Las Computadoras Hardware Ii
Sem3 En El Interior De Las Computadoras   Hardware IiSem3 En El Interior De Las Computadoras   Hardware Ii
Sem3 En El Interior De Las Computadoras Hardware Ii
 

Dernier

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 

Dernier (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 

Jhtp5 20 Datastructures

  • 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
  • 2.
  • 3.
  • 4. 20.2 Self-Referential Classes (cont.) Fig 20.1 Self-referential-class objects linked together. 15 10
  • 5.
  • 6.
  • 7. 20.4 Linked Lists (cont.) Fig 20.2 Linked list graphical representation. firstNode ... H D Q lastNode
  • 8. 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 } 30 Self-referential class ListNode contains data and link to nextNode
  • 9. 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 &quot;list&quot; used in printing 44 45 // construct empty List with &quot;list&quot; as the name 46 public List() 47 { 48 this ( &quot;list&quot; ); 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. 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 ; 89 else 90 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
  • 11. 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. 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( &quot;Empty &quot; + name ); 134 return ; 135 } 136 137 System.out.print( &quot;The &quot; + name + &quot; is: &quot; ); 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() + &quot; &quot; ); 143 current = current.nextNode; 144 } 145 146 System.out.println( &quot;&quot; ); 147 } 148 149 } // end class List Traverse list and print node values
  • 13. EmptyListException.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 ( &quot;List&quot; ); // call other EmptyListException constructor 11 } 12 13 // constructor 14 public EmptyListException( String name ) 15 { 16 super ( name + &quot; is empty&quot; ); // call superclass constructor 17 } 18 19 } // end class EmptyListException Exception thrown when program attempts to remove node from empty list
  • 14. 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 = &quot;hello&quot; ; 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 ( Object s) to store in linked-list nodes Insert values in linked list
  • 15. 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() + &quot; removed&quot; ); 32 list.print(); 33 34 removedObject = list.removeFromFront(); 35 System.out.println( removedObject.toString() + &quot; removed&quot; ); 36 list.print(); 37 38 removedObject = list.removeFromBack(); 39 System.out.println( removedObject.toString() + &quot; removed&quot; ); 40 list.print(); 41 42 removedObject = list.removeFromBack(); 43 System.out.println( removedObject.toString() + &quot; removed&quot; ); 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. 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. 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. 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. 20.4 Linked Lists (cont.) Fig 20.8 Graphical representation of operation removeFromFront . firstNode 12 (a) (b) 7 11 5 lastNode lastNode firstNode removeItem 12 7 11 5
  • 20. 20.4 Linked Lists (cont.) Fig 20.9 Graphical representation of operation removeFromBack . 12 (a) (b) lastNode 7 11 5 lastNode firstNode removeItem firstNode current 12 7 11 5
  • 21.
  • 22. StackInheritance.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 ( &quot;stack&quot; ); 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. StackInheritanceTest.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 = &quot;hello&quot; ; 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 ( Object s) to store in stack Insert values in stack
  • 24. StackInheritanceTest.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() + &quot; popped&quot; ); 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. StackInheritanceTest.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. StackComposition.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( &quot;stack&quot; ); 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. StackComposition.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.
  • 29. 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( &quot;queue&quot; ); 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. 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. 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 = &quot;hello&quot; ; 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 ( Object s) to store in queue Insert values in queue
  • 32. 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() + &quot; dequeued&quot; ); 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. 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.
  • 35.
  • 36. 20.7 Trees (cont.) Fig 20.15 Binary tree graphical representation. B A D C
  • 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. 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 ); 29 Left and right children If value of inserted node is less than value of tree node, insert node in left subtree
  • 39. 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. 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 + &quot; &quot; ); // 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 ); 90 } 91 Preorder traversal – obtain data, traverse left subtree, then traverse right subtree
  • 41. 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 + &quot; &quot; ); // 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 + &quot; &quot; ); // 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. 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( &quot;Inserting the following values: &quot; ); 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 + &quot; &quot; ); 18 tree.insertNode( value ); 19 } 20 21 System.out.println ( &quot;Preorder traversal&quot; ); 22 tree.preorderTraversal(); // perform preorder traversal of tree 23 24 System.out.println ( &quot;Inorder traversal&quot; ); 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. TreeTest.java Line 28 26 27 System.out.println ( &quot;Postorder traversal&quot; ); 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. 20.7 Trees (cont.) Fig 20.19 Binary search tree with seven values. 27 6 17 33 48 13 42