wanted a data structure assignment

profileAshmeet
SourceCode.zip

Chap12/ArrayStack/jsjf/ArrayStack.java

Chap12/ArrayStack/jsjf/ArrayStack.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . Arrays ;

/**
 * An array implementation of a stack in which the bottom of the
 * stack is fixed at index 0.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayStack < T >   implements   StackADT < T >
{
     private   final   static   int  DEFAULT_CAPACITY  =   100 ;

     private   int  top ;   
     private  T []  stack ;

     /**
     * Creates an empty stack using the default capacity.
     */
     public   ArrayStack ()
     {
         this ( DEFAULT_CAPACITY );
     }

     /**
     * Creates an empty stack using the specified capacity.
     *  @param  initialCapacity the initial size of the array 
     */
     public   ArrayStack ( int  initialCapacity )
     {
        top  =   0 ;
        stack  =   ( T [])( new   Object [ initialCapacity ]);
     }

     /**
     * Adds the specified element to the top of this stack, expanding
     * the capacity of the array if necessary.
     *  @param  element generic element to be pushed onto stack
     */
     public   void  push ( T element )
     {
         if   ( size ()   ==  stack . length )  
            expandCapacity ();

        stack [ top ]   =  element ;
        top ++ ;
     }

     /**
     * Creates a new array to store the contents of this stack with
     * twice the capacity of the old one.
     */
     private   void  expandCapacity ()
     {
        stack  =   Arrays . copyOf ( stack ,  stack . length  *   2 );    
     }

     /**
     * Removes the element at the top of this stack and returns a
     * reference to it. 
     *  @return  element removed from top of stack
     *  @throws  EmptyCollectionException if stack is empty 
     */
     public  T pop ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "stack" );

        top -- ;
        T result  =  stack [ top ];
        stack [ top ]   =   null ;  

         return  result ;
     }

     /**
     * Returns a reference to the element at the top of this stack.
     * The element is not removed from the stack.  
     *  @return  element on top of stack
     *  @throws  EmptyCollectionException if stack is empty
     */
     public  T peek ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "stack" );

         return  stack [ top - 1 ];
     }

     /**
     * Returns true if this stack is empty and false otherwise. 
     *  @return  true if this stack is empty
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements in this stack.
     *  @return  the number of elements in the stack
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this stack. 
     *  @return  a string representation of the stack
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }
}

Chap12/ArrayStack/jsjf/exceptions/EmptyCollectionException.java

Chap12/ArrayStack/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException ( String  collection )
     {
         super ( "The "   +  collection  +   " is empty." );
     }
}

Chap12/ArrayStack/jsjf/StackADT.java

Chap12/ArrayStack/jsjf/StackADT.java

package  jsjf ;

/**
 * Defines the interface to a stack collection.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   StackADT < T >
{
     /**  
     * Adds the specified element to the top of this stack. 
     *  @param  element element to be pushed onto the stack
     */
     public   void  push ( T element );

     /**  
     * Removes and returns the top element from this stack. 
     *  @return  the element removed from the stack
     */
     public  T pop ();

     /**  
     * Returns without removing the top element of this stack. 
     *  @return  the element on top of the stack
     */
     public  T peek ();

     /**  
     * Returns true if this stack contains no elements. 
     *  @return  true if the stack is empty
     */
     public   boolean  isEmpty ();

     /** 
     * Returns the number of elements in this stack. 
     *  @return  the number of elements in the stack
     */
     public   int  size ();

     /**  
     * Returns a string representation of this stack. 
     *  @return  a string representation of the stack
     */
     public   String  toString ();
}

Chap12/PostfixTester/PostfixEvaluator.java

Chap12/PostfixTester/PostfixEvaluator.java

import  java . util . Stack ;
import  java . util . Scanner ;

/**
 * Represents an integer evaluator of postfix expressions. Assumes 
 * the operands are constants.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   PostfixEvaluator
{
     private   final   static   char  ADD  =   '+' ;
     private   final   static   char  SUBTRACT  =   '-' ;
     private   final   static   char  MULTIPLY  =   '*' ;
     private   final   static   char  DIVIDE  =   '/' ;

     private   Stack < Integer >  stack ;

     /**
     * Sets up this evaluator by creating a new stack.
     */
     public   PostfixEvaluator ()
     {
        stack  =   new   Stack < Integer > ();
     }

     /**
     * Evaluates the specified postfix expression. If an operand is
     * encountered, it is pushed onto the stack. If an operator is
     * encountered, two operands are popped, the operation is
     * evaluated, and the result is pushed onto the stack.
     *  @param  expr string representation of a postfix expression
     *  @return  value of the given expression
     */
     public   int  evaluate ( String  expr )
     {
         int  op1 ,  op2 ,  result  =   0 ;
         String  token ;
         Scanner  parser  =   new   Scanner ( expr );

         while   ( parser . hasNext ())
         {
            token  =  parser . next ();

             if   ( isOperator ( token ))
             {
                op2  =   ( stack . pop ()). intValue ();
                op1  =   ( stack . pop ()). intValue ();
                result  =  evaluateSingleOperator ( token . charAt ( 0 ),  op1 ,  op2 );
                stack . push ( new   Integer ( result ));
             }
             else
                stack . push ( new   Integer ( Integer . parseInt ( token )));
         }

         return  result ;
     }

     /**
     * Determines if the specified token is an operator.
     *  @param  token the token to be evaluated 
     *  @return  true if token is operator
     */
     private   boolean  isOperator ( String  token )
     {
         return   (  token . equals ( "+" )   ||  token . equals ( "-" )   ||
                token . equals ( "*" )   ||  token . equals ( "/" )   );
     }

     /**
     * Performs integer evaluation on a single expression consisting of 
     * the specified operator and operands.
     *  @param  operation operation to be performed
     *  @param  op1 the first operand
     *  @param  op2 the second operand
     *  @return  value of the expression
     */
     private   int  evaluateSingleOperator ( char  operation ,   int  op1 ,   int  op2 )
     {
         int  result  =   0 ;

         switch   ( operation )
         {
         case  ADD :
            result  =  op1  +  op2 ;
             break ;
         case  SUBTRACT :
            result  =  op1  -  op2 ;
             break ;
         case  MULTIPLY :
            result  =  op1  *  op2 ;
             break ;
         case  DIVIDE :
            result  =  op1  /  op2 ;
         }

         return  result ;
     }
}

Chap12/PostfixTester/PostfixTester.java

Chap12/PostfixTester/PostfixTester.java

import  java . util . Scanner ;

/**
 * Demonstrates the use of a stack to evaluate postfix expressions.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   PostfixTester     
{
     /**
     * Reads and evaluates multiple postfix expressions.
     */
     public   static   void  main ( String []  args )
     {
         String  expression ,  again ;
         int  result ;

         Scanner  in  =   new   Scanner ( System . in );

         do
         {   
             PostfixEvaluator  evaluator  =   new   PostfixEvaluator ();
             System . out . println ( "Enter a valid post-fix expression one token "   +
                     "at a time with a space between each token (e.g. 5 4 + 3 2 1 - + *)" );
             System . out . println ( "Each token must be an integer or an operator (+,-,*,/)" );
            expression  =  in . nextLine ();

            result  =  evaluator . evaluate ( expression );
             System . out . println ();
             System . out . println ( "That expression equals "   +  result );

             System . out . print ( "Evaluate another expression [Y/N]? " );
            again  =  in . nextLine ();
             System . out . println ();
         }
         while   ( again . equalsIgnoreCase ( "y" ));
     }
}

Chap13/LinkedStack/jsjf/exceptions/EmptyCollectionException.java

Chap13/LinkedStack/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException ( String  collection )
     {
         super ( "The "   +  collection  +   " is empty." );
     }
}

Chap13/LinkedStack/jsjf/LinearNode.java

Chap13/LinkedStack/jsjf/LinearNode.java

package  jsjf ;

/**
 * Represents a node in a linked list.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinearNode < T >
{
     private   LinearNode < T >  next ;
     private  T element ;

     /**
     * Creates an empty node.
     */
     public   LinearNode ()
     {
        next  =   null ;
        element  =   null ;
     }

     /**
     * Creates a node storing the specified element.
     *  @param  elem element to be stored
     */
     public   LinearNode ( T elem )
     {
        next  =   null ;
        element  =  elem ;
     }

     /**
     * Returns the node that follows this one.
     *  @return  reference to next node
     */
     public   LinearNode < T >  getNext ()
     {
         return  next ;
     }

     /**
     * Sets the node that follows this one.
     *  @param  node node to follow this one
     */
     public   void  setNext ( LinearNode < T >  node )
     {
        next  =  node ;
     }

     /**
     * Returns the element stored in this node.
     *  @return  element stored at the node
     */
     public  T getElement ()
     {
         return  element ;
     }

     /**
     * Sets the element stored in this node.
     *  @param  elem element to be stored at this node
     */
     public   void  setElement ( T elem )
     {
        element  =  elem ;
     }
}

Chap13/LinkedStack/jsjf/LinkedStack.java

Chap13/LinkedStack/jsjf/LinkedStack.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * Represents a linked implementation of a stack.
 *
 *  @author  Java Foundations 
 *  @version  4.0
 */
public   class   LinkedStack < T >   implements   StackADT < T >
{
     private   int  count ;   
     private   LinearNode < T >  top ;  

     /**
     * Creates an empty stack.
     */
     public   LinkedStack ()
     {
        count  =   0 ;
        top  =   null ;
     }

     /**
     * Adds the specified element to the top of this stack.
     *  @param  element element to be pushed on stack
     */
     public   void  push ( T element )
     {
         LinearNode < T >  temp  =   new   LinearNode < T > ( element );

        temp . setNext ( top );
        top  =  temp ;
        count ++ ;
     }

     /**
     * Removes the element at the top of this stack and returns a
     * reference to it. 
     *  @return  element from top of stack
     *  @throws  EmptyCollectionException if the stack is empty
     */
     public  T pop ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "stack" );

        T result  =  top . getElement ();
        top  =  top . getNext ();
        count -- ;

         return  result ;
     }

     /**
     * Returns a reference to the element at the top of this stack.
     * The element is not removed from the stack.  
     *  @return  element on top of stack
     *  @throws  EmptyCollectionException if the stack is empty  
     */
     public  T peek ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this stack is empty and false otherwise. 
     *  @return  true if stack is empty
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements in this stack.
     *  @return  number of elements in the stack
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this stack. 
     *  @return  string representation of the stack
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }
}

Chap13/LinkedStack/jsjf/StackADT.java

Chap13/LinkedStack/jsjf/StackADT.java

package  jsjf ;

/**
 * Defines the interface to a stack collection.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   StackADT < T >
{
     /**  
     * Adds the specified element to the top of this stack. 
     *  @param  element element to be pushed onto the stack
     */
     public   void  push ( T element );

     /**  
     * Removes and returns the top element from this stack. 
     *  @return  the element removed from the stack
     */
     public  T pop ();

     /**  
     * Returns without removing the top element of this stack. 
     *  @return  the element on top of the stack
     */
     public  T peek ();

     /**  
     * Returns true if this stack contains no elements. 
     *  @return  true if the stack is empty
     */
     public   boolean  isEmpty ();

     /** 
     * Returns the number of elements in this stack. 
     *  @return  the number of elements in the stack
     */
     public   int  size ();

     /**  
     * Returns a string representation of this stack. 
     *  @return  a string representation of the stack
     */
     public   String  toString ();
}

Chap13/MazeTester/Maze.java

Chap13/MazeTester/Maze.java

import  java . util . * ;
import  java . io . * ;

/**
 * Maze represents a maze of characters. The goal is to get from the
 * top left corner to the bottom right, following a path of 1's. Arbitrary
 * constants are used to represent locations in the maze that have been TRIED
 * and that are part of the solution PATH.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   Maze
{
     private   static   final   int  TRIED  =   2 ;
     private   static   final   int  PATH  =   3 ;

     private   int  numberRows ,  numberColumns ;
     private   int [][]  grid ;

     /**
     * Constructor for the Maze class. Loads a maze from the given file.  
     * Throws a FileNotFoundException if the given file is not found.
     *
     *  @param  filename the name of the file to load
     *  @throws  FileNotFoundException if the given file is not found
     */
     public   Maze ( String  filename )   throws   FileNotFoundException
     {
         Scanner  scan  =   new   Scanner ( new   File ( filename ));
        numberRows  =  scan . nextInt ();
        numberColumns  =  scan . nextInt ();

        grid  =   new   int [ numberRows ][ numberColumns ];
         for   ( int  i  =   0 ;  i  <  numberRows ;  i ++ )
             for   ( int  j  =   0 ;  j  <  numberColumns ;  j ++ )
                grid [ i ][ j ]   =  scan . nextInt ();
     }

     /**
     * Marks the specified position in the maze as TRIED
     *
     *  @param  row the index of the row to try
     *  @param  col the index of the column to try 
     */
     public   void  tryPosition ( int  row ,   int  col )
     {
        grid [ row ][ col ]   =  TRIED ;
     }

     /**
     * Return the number of rows in this maze
     *
     *  @return  the number of rows in this maze
     */
     public   int  getRows ()
     {
         return  grid . length ;
     }

     /**
     * Return the number of columns in this maze
     *
     *  @return  the number of columns in this maze
     */
     public   int  getColumns ()
     {
         return  grid [ 0 ]. length ;
     }

     /**
     * Marks a given position in the maze as part of the PATH
     *
     *  @param  row the index of the row to mark as part of the PATH
     *  @param  col the index of the column to mark as part of the PATH 
     */
     public   void  markPath ( int  row ,   int  col )
     {
        grid [ row ][ col ]   =  PATH ;
     }

     /**
     * Determines if a specific location is valid. A valid location
     * is one that is on the grid, is not blocked, and has not been TRIED.
     *
     *  @param  row the row to be checked
     *  @param  column the column to be checked
     *  @return  true if the location is valid    
     */
     public   boolean  validPosition ( int  row ,   int  column )
     {
         boolean  result  =   false ;

         // check if cell is in the bounds of the matrix 
         if   ( row  >=   0   &&  row  <  grid . length  &&
                column  >=   0   &&  column  <  grid [ row ]. length )

             //  check if cell is not blocked and not previously tried 
             if   ( grid [ row ][ column ]   ==   1 )
                result  =   true ;

         return  result ;
     }

     /**
     * Returns the maze as a string.
     * 
     *  @return  a string representation of the maze
     */
     public   String  toString ()
     {
         String  result  =   "\n" ;

         for   ( int  row  =   0 ;  row  <  grid . length ;  row ++ )
         {
             for   ( int  column  =   0 ;  column  <  grid [ row ]. length ;  column ++ )
                result  +=  grid [ row ][ column ]   +   "" ;
            result  +=   "\n" ;
         }

         return  result ;
     }
}

Chap13/MazeTester/MazeSolver.java

Chap13/MazeTester/MazeSolver.java

import  java . util . * ;

/**
 * MazeSolver attempts to traverse a Maze using a stack. The goal is to get from the
 * given starting position to the bottom right, following a path of 1's. Arbitrary
 * constants are used to represent locations in the maze that have been TRIED
 * and that are part of the solution PATH.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   MazeSolver
{
     private   Maze  maze ;

     /**
     * Constructor for the MazeSolver class.
     */
     public   MazeSolver ( Maze  maze )
     {
         this . maze  =  maze ;
     }

     /**
     * Attempts to traverse the maze using a stack. Inserts special
     * characters indicating locations that have been TRIED and that
     * eventually become part of the solution PATH.
     *
     *  @param  row row index of current location
     *  @param  column column index of current location
     *  @return  true if the maze has been solved
     */
     public   boolean  traverse ()
     {
         boolean  done  =   false ;
         Position  pos  =   new   Position ();
         Deque < Position >  stack  =   new   LinkedList < Position > ();
        stack . push ( pos );

         while   ( ! ( done )   &&   ! stack . isEmpty ())
         {
            pos  =  stack . pop ();
            maze . tryPosition ( pos . getx (), pos . gety ());    // this cell has been tried
             if   ( pos . getx ()   ==  maze . getRows () - 1   &&  pos . gety ()   ==  maze . getColumns () - 1 )
                done  =   true ;    // the maze is solved
             else
             {
                pushNewPos ( pos . getx ()   -   1 , pos . gety (),  stack );  
                pushNewPos ( pos . getx ()   +   1 , pos . gety (),  stack );
                pushNewPos ( pos . getx (), pos . gety ()   -   1 ,  stack );
                pushNewPos ( pos . getx (), pos . gety ()   +   1 ,  stack );  
             }
         }

         return  done ;
     }

     /**
     * Push a new attempted move onto the stack
     *  @param  x represents x coordinate
     *  @param  y represents y coordinate
     *  @param  stack the working stack of moves within the grid
     *  @return  stack of moves within the grid
     */
     private   void  pushNewPos ( int  x ,   int  y ,  
             Deque < Position >  stack )
     {
         Position  npos  =   new   Position ();
        npos . setx ( x );
        npos . sety ( y );
         if   ( maze . validPosition ( x , y ))
            stack . push ( npos );
     }

}

Chap13/MazeTester/MazeTester.java

Chap13/MazeTester/MazeTester.java

import  java . util . * ;
import  java . io . * ;

/**
 * MazeTester determines if a maze can be traversed.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   MazeTester
{
     /**
     * Creates a new maze, prints its original form, attempts to
     * solve it, and prints out its final form.
     */
     public   static   void  main ( String []  args )   throws   FileNotFoundException
     {
         Scanner  scan  =   new   Scanner ( System . in );
         System . out . print ( "Enter the name of the file containing the maze: " );
         String  filename  =  scan . nextLine ();

         Maze  labyrinth  =   new   Maze ( filename );

         System . out . println ( labyrinth );

         MazeSolver  solver  =   new   MazeSolver ( labyrinth );

         if   ( solver . traverse ())
             System . out . println ( "The maze was successfully traversed!" );
         else
             System . out . println ( "There is no possible path." );

         System . out . println ( labyrinth );
     }
}

Chap13/MazeTester/Position.java

Chap13/MazeTester/Position.java

/**
 * Represents a single position in a maze of characters.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   Position
{
     private   int  x ;  
     private   int  y ;

     /**
     * Constructs a position and sets the x & y coordinates to 0,0.
     */
     Position   ()
     {
        x  =   0 ;
        y  =   0 ;
     }

     /**
     * Returns the x-coordinate value of this position.
     *  @return  the x-coordinate of this position
     */
     public   int  getx ()
     {
         return  x ;
     }

     /**
     * Returns the y-coordinate value of this position.
     *  @return  the y-coordinate of this position
     */
     public   int  gety ()
     {
         return  y ;
     }

     /**
     * Sets the value of the current position's x-coordinate.
     *  @param  a value of x-coordinate
     */
     public   void  setx ( int  a )
     {
        x  =  a ;
     }

     /**
     * Sets the value of the current position's x-coordinate.
     *  @param  a value of y-coordinate
     */  
     public   void  sety ( int  a )
     {
        y  =  a ;
     }
}

Chap13/MazeTester/testfile.txt

5 5 1 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 1 1

Chap13/MazeTester/testfile2.txt

21 35 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1

Chap13/MazeTester/testfile3.txt

21 35 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 1 1 1 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 1 0 1

Chap13/MazeTester/testfile4.txt

9 13 1 1 1 0 1 1 0 0 0 1 1 1 1 1 0 0 1 1 0 1 1 1 1 0 0 1 1 1 1 1 1 0 1 0 1 0 1 0 0 0 0 0 0 1 1 1 0 1 0 1 1 1 1 1 1 0 1 1 1 0 1 0 1 1 1 1 0 1 0 0 0 0 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1

Chap14/CircularArrayQueue/jsjf/CircularArrayQueue.java

Chap14/CircularArrayQueue/jsjf/CircularArrayQueue.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * CircularArrayQueue represents an array implementation of a queue in 
 * which the indexes for the front and rear of the queue circle back to 0
 * when they reach the end of the array.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   CircularArrayQueue < T >   implements   QueueADT < T >
{
     private   final   static   int  DEFAULT_CAPACITY  =   100 ;
     private   int  front ,  rear ,  count ;
     private  T []  queue ;  

     /**
     * Creates an empty queue using the specified capacity.
     *  @param  initialCapacity the initial size of the circular array queue
     */
     public   CircularArrayQueue ( int  initialCapacity )
     {
        front  =  rear  =  count  =   0 ;
        queue  =   ( T [])   ( new   Object [ initialCapacity ]);
     }

     /**
     * Creates an empty queue using the default capacity.
     */
     public   CircularArrayQueue ()
     {
         this ( DEFAULT_CAPACITY );
     }     

     /**
     * Adds the specified element to the rear of this queue, expanding
     * the capacity of the queue array if necessary.
     *  @param  element the element to add to the rear of the queue
     */
     public   void  enqueue ( T element )
     {
         if   ( size ()   ==  queue . length )  
            expandCapacity ();

        queue [ rear ]   =  element ;
        rear  =   ( rear  +   1 )   %  queue . length ;

        count ++ ;
     }

     /**
     * Creates a new array to store the contents of this queue with
     * twice the capacity of the old one.
     */
     private   void  expandCapacity ()
     {
        T []  larger  =   ( T [])   ( new   Object [ queue . length  *   2 ]);

         for   ( int  scan  =   0 ;  scan  <  count ;  scan ++ )
         {
            larger [ scan ]   =  queue [ front ];
            front  =   ( front  +   1 )   %  queue . length ;
         }

        front  =   0 ;
        rear  =  count ;
        queue  =  larger ;
     }

     /**
     * Removes the element at the front of this queue and returns a
     * reference to it. 
     *  @return  the element removed from the front of the queue
     *  @throws  EmptyCollectionException  if the queue is empty
     */
     public  T dequeue ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "queue" );

        T result  =  queue [ front ];
        queue [ front ]   =   null ;
        front  =   ( front  +   1 )   %  queue . length ;

        count -- ;

         return  result ;
     }

     /** 
     * Returns a reference to the element at the front of this queue.
     * The element is not removed from the queue.  
     *  @return  the first element in the queue
     *  @throws  EmptyCollectionException if the queue is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this queue is empty and false otherwise.
     *  @return  true if this queue is empty 
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements currently in this queue.
     *  @return  the size of the queue
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this queue. 
     *  @return  the string representation of the queue
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }
}

Chap14/CircularArrayQueue/jsjf/exceptions/EmptyCollectionException.java

Chap14/CircularArrayQueue/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException ( String  collection )
     {
         super ( "The "   +  collection  +   " is empty." );
     }
}

Chap14/CircularArrayQueue/jsjf/QueueADT.java

Chap14/CircularArrayQueue/jsjf/QueueADT.java

package  jsjf ;

/**
 * QueueADT defines the interface to a queue collection.
 *
 *  @author  Java Foundation
 *  @version  4.0
 */
public   interface   QueueADT < T >
{
     /**  
     * Adds one element to the rear of this queue. 
     *  @param  element  the element to be added to the rear of the queue  
     */
     public   void  enqueue ( T element );

     /**  
     * Removes and returns the element at the front of this queue.
     *  @return  the element at the front of the queue
     */
     public  T dequeue ();

     /**  
     * Returns without removing the element at the front of this queue.
     *  @return  the first element in the queue
     */
     public  T first ();

     /**  
     * Returns true if this queue contains no elements.
     *  @return  true if this queue is empty
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this queue. 
     *  @return  the integer representation of the size of the queue
     */
     public   int  size ();

     /**  
     * Returns a string representation of this queue. 
     *  @return  the string representation of the queue
     */
     public   String  toString ();
}

Chap14/Codes/Codes.java

Chap14/Codes/Codes.java

import  java . util . * ;

/**
 * Codes demonstrates the use of queues to encrypt and decrypt messages.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   Codes
{
     /**
     * Encode and decode a message using a key of values stored in
     * a queue.
     */
     public   static   void  main ( String []  args )
     {  
         int []  key  =   { 5 ,   12 ,   - 3 ,   8 ,   - 9 ,   4 ,   10 };
         Integer  keyValue ;
         String  encoded  =   "" ,  decoded  =   "" ;
        
         String  message  =   "All programmers are playwrights and all "   +
                 "computers are lousy actors." ;
        
         Queue < Integer >  encodingQueue  =   new   LinkedList < Integer > ();
         Queue < Integer >  decodingQueue  =   new   LinkedList < Integer > ();

         // load key queues 
         for   ( int  scan  =   0 ;  scan  <  key . length ;  scan ++ )
         {
            encodingQueue . add ( key [ scan ]);
            decodingQueue . add ( key [ scan ]);
         }

         // encode message 
         for   ( int  scan  =   0 ;  scan  <  message . length ();  scan ++ )
         {
            keyValue  =  encodingQueue . remove ();
            encoded  +=   ( char )   ( message . charAt ( scan )   +  keyValue );
            encodingQueue . add ( keyValue );
         }

         System . out . println  ( "Encoded Message:\n"   +  encoded  +   "\n" );

         // decode message 
         for   ( int  scan  =   0 ;  scan  <  encoded . length ();  scan ++ )
         {
            keyValue  =  decodingQueue . remove ();
            decoded  +=   ( char )   ( encoded . charAt ( scan )   -  keyValue );
            decodingQueue . add ( keyValue );
         }

         System . out . println  ( "Decoded Message:\n"   +  decoded );
     }
}

Chap14/LinkedQueue/jsjf/exceptions/EmptyCollectionException.java

Chap14/LinkedQueue/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException ( String  collection )
     {
         super ( "The "   +  collection  +   " is empty." );
     }
}

Chap14/LinkedQueue/jsjf/LinearNode.java

Chap14/LinkedQueue/jsjf/LinearNode.java

package  jsjf ;

/**
 * Represents a node in a linked list.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinearNode < T >
{
     private   LinearNode < T >  next ;
     private  T element ;

     /**
     * Creates an empty node.
     */
     public   LinearNode ()
     {
        next  =   null ;
        element  =   null ;
     }

     /**
     * Creates a node storing the specified element.
     *  @param  elem element to be stored
     */
     public   LinearNode ( T elem )
     {
        next  =   null ;
        element  =  elem ;
     }

     /**
     * Returns the node that follows this one.
     *  @return  reference to next node
     */
     public   LinearNode < T >  getNext ()
     {
         return  next ;
     }

     /**
     * Sets the node that follows this one.
     *  @param  node node to follow this one
     */
     public   void  setNext ( LinearNode < T >  node )
     {
        next  =  node ;
     }

     /**
     * Returns the element stored in this node.
     *  @return  element stored at the node
     */
     public  T getElement ()
     {
         return  element ;
     }

     /**
     * Sets the element stored in this node.
     *  @param  elem element to be stored at this node
     */
     public   void  setElement ( T elem )
     {
        element  =  elem ;
     }
}

Chap14/LinkedQueue/jsjf/LinkedQueue.java

Chap14/LinkedQueue/jsjf/LinkedQueue.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * LinkedQueue represents a linked implementation of a queue.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinkedQueue < T >   implements   QueueADT < T >
{
     private   int  count ;
     private   LinearNode < T >  head ,  tail ;

     /**
     * Creates an empty queue.
     */
     public   LinkedQueue ()
     {
        count  =   0 ;
        head  =  tail  =   null ;
     }

     /**
     * Adds the specified element to the tail of this queue.
     *  @param  element the element to be added to the tail of the queue
     */
     public   void  enqueue ( T element )
     {
         LinearNode < T >  node  =   new   LinearNode < T > ( element );

         if   ( isEmpty ())
            head  =  node ;
         else
            tail . setNext ( node );

        tail  =  node ;
        count ++ ;
     }

     /**
     * Removes the element at the head of this queue and returns a
     * reference to it. 
     *  @return  the element at the head of this queue
     *  @throws  EmptyCollectionException if the queue is empty
     */
     public  T dequeue ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "queue" );

        T result  =  head . getElement ();
        head  =  head . getNext ();
        count -- ;

         if   ( isEmpty ())
            tail  =   null ;

         return  result ;
     }

     /**
     * Returns a reference to the element at the head of this queue.
     * The element is not removed from the queue.  
     *  @return  a reference to the first element in this queue
     *  @throws  EmptyCollectionsException if the queue is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this queue is empty and false otherwise. 
     *  @return  true if this queue is empty 
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements currently in this queue.
     *  @return  the number of elements in the queue
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this queue. 
     *  @return  the string representation of the queue
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }
}

Chap14/LinkedQueue/jsjf/QueueADT.java

Chap14/LinkedQueue/jsjf/QueueADT.java

package  jsjf ;

/**
 * QueueADT defines the interface to a queue collection.
 *
 *  @author  Java Foundation
 *  @version  4.0
 */
public   interface   QueueADT < T >
{
     /**  
     * Adds one element to the rear of this queue. 
     *  @param  element  the element to be added to the rear of the queue  
     */
     public   void  enqueue ( T element );

     /**  
     * Removes and returns the element at the front of this queue.
     *  @return  the element at the front of the queue
     */
     public  T dequeue ();

     /**  
     * Returns without removing the element at the front of this queue.
     *  @return  the first element in the queue
     */
     public  T first ();

     /**  
     * Returns true if this queue contains no elements.
     *  @return  true if this queue is empty
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this queue. 
     *  @return  the integer representation of the size of the queue
     */
     public   int  size ();

     /**  
     * Returns a string representation of this queue. 
     *  @return  the string representation of the queue
     */
     public   String  toString ();
}

Chap14/TicketCounter/Customer.java

Chap14/TicketCounter/Customer.java

/**
 * Customer represents a waiting customer.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   Customer
{
     private   int  arrivalTime ,  departureTime ;

     /**
     * Creates a new customer with the specified arrival time.
     *  @param  arrives the arrival time
     */
     public   Customer ( int  arrives )
     {
        arrivalTime  =  arrives ;
        departureTime  =   0 ;
     }

     /**
     * Returns the arrival time of this customer.
     *  @return  the arrival time
     */
     public   int  getArrivalTime ()
     {
         return  arrivalTime ;
     }

     /**
     * Sets the departure time for this customer.
     *  @param  departs the departure time
     **/
     public   void  setDepartureTime ( int  departs )
     {
        departureTime  =  departs ;
     }

     /**
     * Returns the departure time of this customer.
     *  @return  the departure time
     */
     public   int  getDepartureTime ()
     {
         return  departureTime ;
     }

     /**
     * Computes and returns the total time spent by this customer.
     *  @return  the total customer time
     */
     public   int  totalTime ()
     {
         return  departureTime  -  arrivalTime ;
     }
}

Chap14/TicketCounter/TicketCounter.java

Chap14/TicketCounter/TicketCounter.java

import  java . util . * ;

/**
 * TicketCounter demonstrates the use of a queue for simulating a line of customers.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   TicketCounter     
{
     private   final   static   int  PROCESS  =   120 ;
     private   final   static   int  MAX_CASHIERS  =   10 ;
     private   final   static   int  NUM_CUSTOMERS  =   100 ;

     public   static   void  main ( String []  args )
     {
         Customer  customer ;
         Queue < Customer >  customerQueue  =   new   LinkedList < Customer > ();
         int []  cashierTime  =   new   int [ MAX_CASHIERS ];   
         int  totalTime ,  averageTime ,  departs ,  start ;

         // run the simulation for various number of cashiers 
         for   ( int  cashiers  =   0 ;  cashiers  <  MAX_CASHIERS ;  cashiers ++ )
         {  
             // set each cashiers time to zero initially
             for   ( int  count  =   0 ;  count  <  cashiers ;  count ++ )
                cashierTime [ count ]   =   0 ;

             // load customer queue 
             for   ( int  count  =   1 ;  count  <=  NUM_CUSTOMERS ;  count ++ )
                customerQueue . add ( new   Customer ( count  *   15 ));

            totalTime  =   0 ;

             // process all customers in the queue 
             while   ( ! ( customerQueue . isEmpty ()))  
             {
                 for   ( int  count  =   0 ;  count  <=  cashiers ;  count ++ )
                 {
                     if   ( ! ( customerQueue . isEmpty ()))
                     {
                        customer  =  customerQueue . remove ();
                         if   ( customer . getArrivalTime ()   >  cashierTime [ count ])
                            start  =  customer . getArrivalTime ();
                         else
                            start  =  cashierTime [ count ];  
                        departs  =  start  +  PROCESS ;
                        customer . setDepartureTime ( departs );
                        cashierTime [ count ]   =  departs ;
                        totalTime  +=  customer . totalTime ();
                     }
                 }
             }

             // output results for this simulation 
            averageTime  =  totalTime  /  NUM_CUSTOMERS ;
             System . out . println ( "Number of cashiers: "   +   ( cashiers  +   1 ));
             System . out . println ( "Average time: "   +  averageTime  +   "\n" );
         }
     }
}

Chap15/ArrayList/jsjf/ArrayList.java

Chap15/ArrayList/jsjf/ArrayList.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . * ;

/**
 * ArrayList represents an array implementation of a list. The front of
 * the list is kept at array index 0. This class will be extended
 * to create a specific kind of list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   abstract   class   ArrayList < T >   implements   ListADT < T > ,   Iterable < T >
{
     private   final   static   int  DEFAULT_CAPACITY  =   100 ;
     private   final   static   int  NOT_FOUND  =   - 1 ;

     protected   int  rear ;
     protected  T []  list ;  
     protected   int  modCount ;

     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayList ()
     {
         this ( DEFAULT_CAPACITY );
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the integer value of the size of the array list
     */
     public   ArrayList ( int  initialCapacity )
     {
        rear  =   0 ;
        list  =   ( T [])( new   Object [ initialCapacity ]);
        modCount  =   0 ;
     }

     /**
     * Creates a new array to store the contents of this list with
     * twice the capacity of the old one. Called by descendant classes
     * that add elements to the list.
     */
     protected   void  expandCapacity ()
     {
         // To be completed as a Programming Project
     }

     /**
     * Removes and returns the last element in this list.
     *
     *  @return  the last element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeLast ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the first element in this list.
     *
     *  @return  the first element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeFirst ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the specified element.
     *
     *  @param   element the element to be removed and returned from the list
     *  @return  the removed elememt
     *  @throws  ElementNotFoundException if the element is not in the list
     */
     public  T remove ( T element )
     {
        T result ;
         int  index  =  find ( element );

         if   ( index  ==  NOT_FOUND )
             throw   new   ElementNotFoundException ( "ArrayList" );

        result  =  list [ index ];
        rear -- ;

         // shift the appropriate elements 
         for   ( int  scan  =  index ;  scan  <  rear ;  scan ++ )
            list [ scan ]   =  list [ scan + 1 ];

        list [ rear ]   =   null ;
        modCount ++ ;

         return  result ;
     }

     /**
     * Returns a reference to the element at the front of this list.
     * The element is not removed from the list.  Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the first element in the list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the element at the rear of this list.
     * The element is not removed from the list. Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the last element of this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T last ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this list contains the specified element.
     *
     *  @param  target the target element
     *  @return  true if the target is in the list, false otherwise 
     */
     public   boolean  contains ( T target )
     {
         return   ( find ( target )   !=  NOT_FOUND );
     }

     /**
     * Returns the array index of the specified element, or the
     * constant NOT_FOUND if it is not found.
     *
     *  @param  target the target element
     *  @return  the index of the target element, or the 
     *         NOT_FOUND constant
     */
     private   int  find ( T target )
     {
         int  scan  =   0 ;  
         int  result  =  NOT_FOUND ;

         if   ( ! isEmpty ())
             while   ( result  ==  NOT_FOUND  &&  scan  <  rear )
                 if   ( target . equals ( list [ scan ]))
                    result  =  scan ;
                 else
                    scan ++ ;

         return  result ;
     }

     /**
     * Returns true if this list is empty and false otherwise. 
     *
     *  @return  true if the list is empty, false otherwise
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements currently in this list.
     *
     *  @return  the number of elements in the list
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this list. 
     * 
     *  @return  the string representation of the list
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }

     /**
     * Returns an iterator for the elements currently in this list.
     * 
     *  @return  an iterator for the elements in the list
     */
     public   Iterator < T >  iterator ()
     {
         return   new   ArrayListIterator ();
     }

     /**
     * ArrayListIterator iterator over the elements of an ArrayList.
     */  
     private   class   ArrayListIterator   implements   Iterator < T >
     {
         int  iteratorModCount ;
         int  current ;

         /**
         * Sets up this iterator using the specified modCount.
         * 
         *  @param  modCount the current modification count for the ArrayList
         */
         public   ArrayListIterator ()
         {
            iteratorModCount  =  modCount ;
            current  =   0 ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( iteratorModCount  !=  modCount )
                 throw   new   ConcurrentModificationException ();

             return   ( current  <  rear );
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return   the next element in the iteration
         *  @throws   NoSuchElementException if an element not found exception occurs
         *  @throws   ConcurrentModificationException if the collection has changed
         */
         public  T next ()   throws   ConcurrentModificationException
         {
             if   ( ! hasNext ())
                 throw   new   NoSuchElementException ();

            current ++ ;

             return  list [ current  -   1 ];
         }

         /**
         * The remove operation is not supported in this collection.
         * 
         *  @throws  UnsupportedOperationException if the remove method is called
         */
         public   void  remove ()   throws   UnsupportedOperationException
         {
             throw   new   UnsupportedOperationException ();
         }

     }    
}

Chap15/ArrayList/jsjf/ArrayOrderedList.java

Chap15/ArrayList/jsjf/ArrayOrderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayOrderedList represents an array implementation of an ordered list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayOrderedList < T >   extends   ArrayList < T >
implements   OrderedListADT < T >
{
     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayOrderedList ()
     {
         super ();
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the initial size of the list
     */
     public   ArrayOrderedList ( int  initialCapacity )
     {
         super ( initialCapacity );
     }

     /**
     * Adds the specified Comparable element to this list, keeping
     * the elements in sorted order.
     *
     *  @param  element the element to be added to the list
     */
     public   void  add ( T element )
     {
         if   ( ! ( element  instanceof   Comparable ))
             throw   new   NonComparableElementException ( "OrderedList" );

         Comparable < T >  comparableElement  =   ( Comparable < T > ) element ;

         if   ( size ()   ==  list . length )
            expandCapacity ();

         int  scan  =   0 ;   

         // find the insertion location
         while   ( scan  <  rear  &&  comparableElement . compareTo ( list [ scan ])   >   0 )
            scan ++ ;

         // shift existing elements up one
         for   ( int  shift  =  rear ;  shift  >  scan ;  shift -- )
            list [ shift ]   =  list [ shift  -   1 ];

         // insert element
        list [ scan ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }
}

Chap15/ArrayList/jsjf/ArrayUnorderedList.java

Chap15/ArrayList/jsjf/ArrayUnorderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayUnorderedList represents an array implementation of an unordered list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayUnorderedList < T >   extends   ArrayList < T >  
implements   UnorderedListADT < T >
{
     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayUnorderedList ()
     {
         super ();
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the initial size of the list
     */
     public   ArrayUnorderedList ( int  initialCapacity )
     {
         super ( initialCapacity );
     }

     /**
     * Adds the specified element to the front of this list.
     * 
     *  @param  element the element to be added to the front of the list
     */
     public   void  addToFront ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element to the rear of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToRear ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element after the specified target element.
     * Throws an ElementNotFoundException if the target is not found.
     *
     *  @param  element the element to be added after the target element
     *  @param  target  the target that the element is to be added after
     */
     public   void  addAfter ( T element ,  T target )
     {
         if   ( size ()   ==  list . length )
            expandCapacity ();

         int  scan  =   0 ;

         // find the insertion point
         while   ( scan  <  rear  &&   ! target . equals ( list [ scan ]))  
            scan ++ ;

         if   ( scan  ==  rear )
             throw   new   ElementNotFoundException ( "UnorderedList" );

        scan ++ ;

         // shift elements up one
         for   ( int  shift  =  rear ;  shift  >  scan ;  shift -- )
            list [ shift ]   =  list [ shift  -   1 ];

         // insert element
        list [ scan ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }
}

Chap15/ArrayList/jsjf/exceptions/ElementNotFoundException.java

Chap15/ArrayList/jsjf/exceptions/ElementNotFoundException.java

package  jsjf . exceptions ;

/**
 * ElementNotFoundException represents the situation in which a target element 
 * is not present in a collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ElementNotFoundException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     */
     public   ElementNotFoundException   ( String  collection )
     {
         super   ( "The target element is not in this "   +  collection );
     }
}

Chap15/ArrayList/jsjf/exceptions/EmptyCollectionException.java

Chap15/ArrayList/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException ( String  collection )
     {
         super ( "The "   +  collection  +   " is empty." );
     }
}

Chap15/ArrayList/jsjf/exceptions/NonComparableElementException.java

Chap15/ArrayList/jsjf/exceptions/NonComparableElementException.java

package  jsjf . exceptions ;

/**
 * NonComparableElementException  represents the situation in which an attempt 
 * is made to add an element that is not comparable to an ordered collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   NonComparableElementException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     * 
     *  @param  collection  the exception message to deliver
     */
     public   NonComparableElementException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " requires Comparable elements." );
     }
}

Chap15/ArrayList/jsjf/ListADT.java

Chap15/ArrayList/jsjf/ListADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * ListADT defines the interface to a general list collection. Specific
 * types of lists will extend this interface to complete the
 * set of necessary operations.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   ListADT < T >   extends   Iterable < T >
{
     /**  
     * Removes and returns the first element from this list. 
     * 
     *  @return  the first element from this list
     */
     public  T removeFirst ();

     /**  
     * Removes and returns the last element from this list. 
     *
     *  @return  the last element from this list
     */
     public  T removeLast ();

     /**  
     * Removes and returns the specified element from this list. 
     *
     *  @param  element the element to be removed from the list
     */
     public  T remove ( T element );

     /**  
     * Returns a reference to the first element in this list. 
     *
     *  @return  a reference to the first element in this list
     */
     public  T first ();

     /**  
     * Returns a reference to the last element in this list. 
     *
     *  @return  a reference to the last element in this list
     */
     public  T last ();

     /**  
     * Returns true if this list contains the specified target element. 
     *
     *  @param  target the target that is being sought in the list
     *  @return  true if the list contains this element
     */
     public   boolean  contains ( T target );

     /**  
     * Returns true if this list contains no elements. 
     *
     *  @return  true if this list contains no elements
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this list. 
     *
     *  @return  the integer representation of number of elements in this list
     */
     public   int  size ();

     /**  
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements in this list
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns a string representation of this list. 
     *
     *  @return  a string representation of this list
     */
     public   String  toString ();
}

Chap15/ArrayList/jsjf/OrderedListADT.java

Chap15/ArrayList/jsjf/OrderedListADT.java

package  jsjf ;

/**
 * OrderedListADT defines the interface to an ordered list collection. Only
 * Comparable elements are stored, kept in the order determined by
 * the inherent relationship among the elements.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   OrderedListADT < T >   extends   ListADT < T >
{
     /**
     * Adds the specified element to this list at the proper location
     *
     *  @param  element the element to be added to this list
     */
     public   void  add ( T element );
}

Chap15/ArrayList/jsjf/UnorderedListADT.java

Chap15/ArrayList/jsjf/UnorderedListADT.java

package  jsjf ;

/**
 * UnorderedListADT defines the interface to an unordered list collection. 
 * Elements are stored in any order the user desires.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   UnorderedListADT < T >   extends   ListADT < T >
{
     /**  
     * Adds the specified element to the front of this list. 
     *
     *  @param  element the element to be added to the front of this list    
     */
     public   void  addToFront ( T element );   

     /**  
     * Adds the specified element to the rear of this list. 
     *
     *  @param  element the element to be added to the rear of this list    
     */
     public   void  addToRear ( T element );  

     /**  
     * Adds the specified element after the specified target. 
     *
     *  @param  element the element to be added after the target
     *  @param  target  the target is the item that the element will be added
     *                after    
     */
     public   void  addAfter ( T element ,  T target );
}

Chap15/Josephus/Josephus.java

Chap15/Josephus/Josephus.java

import  java . util . * ;

/**
 * Demonstrates the use of an indexed list to solve the Josephus problem.
 *
 *  @author  Java Foundations 
 *  @version  4.0
 */
public   class   Josephus
{
     /**
     * Continue around the circle eliminating every nth soldier 
     * until all of the soldiers have been eliminated.
     */
     public   static   void  main ( String []  args )
     {
         int  numPeople ,  skip ,  targetIndex ;
         List < String >  list  =   new   ArrayList < String > ();
         Scanner  in  =   new   Scanner ( System . in );

         // get the initial number of soldiers 
         System . out . print ( "Enter the number of soldiers: " );
        numPeople  =  in . nextInt ();
        in . nextLine ();   

         // get the number of soldiers to skip 
         System . out . print ( "Enter the number of soldiers to skip: " );
        skip  =  in . nextInt ();   

         // load the initial list of soldiers 
         for   ( int  count  =   1 ;  count  <=  numPeople ;  count ++ )
         {
            list . add ( "Soldier "   +  count );
         }

        targetIndex  =  skip ;  
         System . out . println ( "The order is: " );

         // Treating the list as circular, remove every nth element
         // until the list is empty 
         while   ( ! list . isEmpty ())  
         {
             System . out . println ( list . remove ( targetIndex ));
             if   ( list . size ()   >   0 )
                targetIndex  =   ( targetIndex  +  skip )   %  list . size ();
         }
     }
}  

Chap15/LinkedList/jsjf/exceptions/ElementNotFoundException.java

Chap15/LinkedList/jsjf/exceptions/ElementNotFoundException.java

package  jsjf . exceptions ;

/**
 * ElementNotFoundException represents the situation in which a target element 
 * is not present in a collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ElementNotFoundException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     */
     public   ElementNotFoundException   ( String  collection )
     {
         super   ( "The target element is not in this "   +  collection );
     }
}

Chap15/LinkedList/jsjf/exceptions/EmptyCollectionException.java

Chap15/LinkedList/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException ( String  collection )
     {
         super ( "The "   +  collection  +   " is empty." );
     }
}

Chap15/LinkedList/jsjf/exceptions/NonComparableElementException.java

Chap15/LinkedList/jsjf/exceptions/NonComparableElementException.java

package  jsjf . exceptions ;

/**
 * NonComparableElementException  represents the situation in which an attempt 
 * is made to add an element that is not comparable to an ordered collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   NonComparableElementException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     * 
     *  @param  collection  the exception message to deliver
     */
     public   NonComparableElementException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " requires Comparable elements." );
     }
}

Chap15/LinkedList/jsjf/LinearNode.java

Chap15/LinkedList/jsjf/LinearNode.java

package  jsjf ;

/**
 * LinearNode represents a node in a linked list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinearNode < E >
{
     private   LinearNode < E >  next ;
     private  E element ;

     /**
     * Creates an empty node.
     */
     public   LinearNode ()
     {
        next  =   null ;
        element  =   null ;
     }

     /**
     * Creates a node storing the specified element.
     *
     *  @param  elem the element to be stored within the new node
     */
     public   LinearNode ( E elem )
     {
        next  =   null ;
        element  =  elem ;
     }

     /**
     * Returns the node that follows this one.
     *
     *  @return  the node that follows the current one
     */
     public   LinearNode < E >  getNext ()
     {
         return  next ;
     }

     /**
     * Sets the node that follows this one.
     *
     *  @param  node the node to be set to follow the current one
     */
     public   void  setNext ( LinearNode < E >  node )
     {
        next  =  node ;
     }

     /**
     * Returns the element stored in this node.
     *
     *  @return  the element stored in this node
     */
     public  E getElement ()
     {
         return  element ;
     }

     /**
     * Sets the element stored in this node.
     *
     *  @param  elem the element to be stored in this node
     */
     public   void  setElement ( E elem )
     {
        element  =  elem ;
     }
}

Chap15/LinkedList/jsjf/LinkedList.java

Chap15/LinkedList/jsjf/LinkedList.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . * ;

/**
 * LinkedList represents a linked implementation of a list.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   abstract   class   LinkedList < T >   implements   ListADT < T > ,   Iterable < T >
{
     protected   int  count ;
     protected   LinearNode < T >  head ,  tail ;
     protected   int  modCount ;

     /**
     * Creates an empty list.
     */
     public   LinkedList ()
     {
        count  =   0 ;
        head  =  tail  =   null ;
        modCount  =   0 ;
     }

     /**
     * Removes the first element in this list and returns a reference
     * to it. Throws an EmptyCollectionException if the list is empty.
     *
     *  @return  a reference to the first element of this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T removeFirst ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes the last element in this list and returns a reference
     * to it. Throws an EmptyCollectionException if the list is empty.
     *
     *  @return  the last element in this list
     *  @throws  EmptyCollectionException if the list is empty    
     */
     public  T removeLast ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes the first instance of the specified element from this
     * list and returns a reference to it. Throws an EmptyCollectionException 
     * if the list is empty. Throws a ElementNotFoundException if the 
     * specified element is not found in the list.
     *
     *  @param   targetElement the element to be removed from the list
     *  @return  a reference to the removed element
     *  @throws  EmptyCollectionException if the list is empty
     *  @throws  ElementNotFoundException if the target element is not found
     */
     public  T remove ( T targetElement )   throws   EmptyCollectionException ,  
     ElementNotFoundException  
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "LinkedList" );

         boolean  found  =   false ;
         LinearNode < T >  previous  =   null ;
         LinearNode < T >  current  =  head ;

         while   ( current  !=   null   &&   ! found )
             if   ( targetElement . equals ( current . getElement ()))
                found  =   true ;
             else
             {
                previous  =  current ;
                current  =  current . getNext ();
             }

         if   ( ! found )
             throw   new   ElementNotFoundException ( "LinkedList" );

         if   ( size ()   ==   1 )    // only one element in the list
            head  =  tail  =   null ;
         else   if   ( current . equals ( head ))    // target is at the head 
            head  =  current . getNext ();
         else   if   ( current . equals ( tail ))    // target is at the tail
         {
            tail  =  previous ;
            tail . setNext ( null );
         }
         else    // target is in the middle
            previous . setNext ( current . getNext ());

        count -- ;
        modCount ++ ;

         return  current . getElement ();
     }

     /**
     * Returns the first element in this list without removing it. 
     *
     *  @return  the first element in this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the last element in this list without removing it. 
     *
     *  @return  the last element in this list  
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T last ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if the specified element is found in this list and 
     * false otherwise. Throws an EmptyCollectionException if the list 
     * is empty.
     *
     *  @param   targetElement the element that is sought in the list
     *  @return  true if the element is found in this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public   boolean  contains ( T targetElement )   throws   EmptyCollectionException  
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns true if this list is empty and false otherwise.
     *
     *  @return  true if the list is empty, false otherwise
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements in this list.
     *
     *  @return  the number of elements in the list
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this list.
     *
     *  @return  a string representation of the list    
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }

     /**
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements of the list
     */
     public   Iterator < T >  iterator ()
     {
         return   new   LinkedListIterator ();
     }

     /**
     * LinkedIterator represents an iterator for a linked list of linear nodes.
     */
     private   class   LinkedListIterator   implements   Iterator < T >
     {
         private   int  iteratorModCount ;    // the number of elements in the collection
         private   LinearNode < T >  current ;    // the current position

         /**
         * Sets up this iterator using the specified items.
         *
         *  @param  collection  the collection the iterator will move over
         *  @param  size        the integer size of the collection
         */
         public   LinkedListIterator ()
         {
            current  =  head ;
            iteratorModCount  =  modCount ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( iteratorModCount  !=  modCount )  
                 throw   new   ConcurrentModificationException ();

             return   ( current  !=   null );
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return  the next element in the iteration
         *  @throws  NoSuchElementException if the iterator is empty
         */
         public  T next ()   throws   ConcurrentModificationException
         {
             if   ( ! hasNext ())
                 throw   new   NoSuchElementException ();

            T result  =  current . getElement ();
            current  =  current . getNext ();
             return  result ;
         }

         /**
         * The remove operation is not supported.
         * 
         *  @throws  UnsupportedOperationException if the remove operation is called
         */
         public   void  remove ()   throws   UnsupportedOperationException
         {
             throw   new   UnsupportedOperationException ();
         }
     }

}


Chap15/LinkedList/jsjf/LinkedOrderedList.java

Chap15/LinkedList/jsjf/LinkedOrderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * LinkedOrderedList represents a singly linked implementation of an 
 * ordered list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinkedOrderedList < T >   extends   LinkedList < T >  
implements   OrderedListADT < T >
{
     /**
     * Creates an empty list.
     */
     public   LinkedOrderedList ()
     {
         super ();
     }

     /**
     * Adds the specified element to this list at the location determined by
     * the element's natural ordering. Throws a NonComparableElementException 
     * if the element is not comparable.
     *
     *  @param  element the element to be added to this list
     *  @throws  NonComparableElementException if the element is not comparable
     */
     public   void  add ( T element )
     {
         // To be completed as a Programming Project
     }
}

Chap15/LinkedList/jsjf/LinkedUnorderedList.java

Chap15/LinkedList/jsjf/LinkedUnorderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * LinkedUnorderedList represents a singly linked implementation of an 
 * unordered list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinkedUnorderedList < T >   extends   LinkedList < T >  
implements   UnorderedListADT < T >
{
     /**
     * Creates an empty list.
     */
     public   LinkedUnorderedList ()
     {
         super ();
     }

     /**
     * Adds the specified element to the front of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToFront ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element to the rear of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToRear ( T element )
     {
         // To be completed as a Programming Project
     }


     /**
     * Adds the specified element to this list after the given target.
     *
     *  @param   element the element to be added to this list
     *  @param   target the target element to be added after
     *  @throws  ElementNotFoundException if the target is not found
     */
     public   void  addAfter ( T element ,  T target )
     {
         // To be completed as a Programming Project
     }    
}

Chap15/LinkedList/jsjf/ListADT.java

Chap15/LinkedList/jsjf/ListADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * ListADT defines the interface to a general list collection. Specific
 * types of lists will extend this interface to complete the
 * set of necessary operations.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   ListADT < T >   extends   Iterable < T >
{
     /**  
     * Removes and returns the first element from this list. 
     * 
     *  @return  the first element from this list
     */
     public  T removeFirst ();

     /**  
     * Removes and returns the last element from this list. 
     *
     *  @return  the last element from this list
     */
     public  T removeLast ();

     /**  
     * Removes and returns the specified element from this list. 
     *
     *  @param  element the element to be removed from the list
     */
     public  T remove ( T element );

     /**  
     * Returns a reference to the first element in this list. 
     *
     *  @return  a reference to the first element in this list
     */
     public  T first ();

     /**  
     * Returns a reference to the last element in this list. 
     *
     *  @return  a reference to the last element in this list
     */
     public  T last ();

     /**  
     * Returns true if this list contains the specified target element. 
     *
     *  @param  target the target that is being sought in the list
     *  @return  true if the list contains this element
     */
     public   boolean  contains ( T target );

     /**  
     * Returns true if this list contains no elements. 
     *
     *  @return  true if this list contains no elements
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this list. 
     *
     *  @return  the integer representation of number of elements in this list
     */
     public   int  size ();

     /**  
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements in this list
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns a string representation of this list. 
     *
     *  @return  a string representation of this list
     */
     public   String  toString ();
}

Chap15/LinkedList/jsjf/OrderedListADT.java

Chap15/LinkedList/jsjf/OrderedListADT.java

package  jsjf ;

/**
 * OrderedListADT defines the interface to an ordered list collection. Only
 * Comparable elements are stored, kept in the order determined by
 * the inherent relationship among the elements.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   OrderedListADT < T >   extends   ListADT < T >
{
     /**
     * Adds the specified element to this list at the proper location
     *
     *  @param  element the element to be added to this list
     */
     public   void  add ( T element );
}

Chap15/LinkedList/jsjf/UnorderedListADT.java

Chap15/LinkedList/jsjf/UnorderedListADT.java

package  jsjf ;

/**
 * UnorderedListADT defines the interface to an unordered list collection. 
 * Elements are stored in any order the user desires.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   UnorderedListADT < T >   extends   ListADT < T >
{
     /**  
     * Adds the specified element to the front of this list. 
     *
     *  @param  element the element to be added to the front of this list    
     */
     public   void  addToFront ( T element );   

     /**  
     * Adds the specified element to the rear of this list. 
     *
     *  @param  element the element to be added to the rear of this list    
     */
     public   void  addToRear ( T element );  

     /**  
     * Adds the specified element after the specified target. 
     *
     *  @param  element the element to be added after the target
     *  @param  target  the target is the item that the element will be added
     *                after    
     */
     public   void  addAfter ( T element ,  T target );
}

Chap15/POSTester/Course.java

Chap15/POSTester/Course.java

import  java . io . Serializable ;

/**
 * Represents a course that might be taken by a student.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   Course   implements   Serializable
{
     private   String  prefix ;
     private   int  number ;
     private   String  title ;
     private   String  grade ;

     /**
     * Constructs the course with the specified information.
     * 
     *  @param  prefix the prefix of the course designation
     *  @param  number the number of the course designation
     *  @param  title the title of the course
     *  @param  grade the grade received for the course
     */
     public   Course ( String  prefix ,   int  number ,   String  title ,   String  grade )
     {
         this . prefix  =  prefix ;
         this . number  =  number ;
         this . title  =  title ;
         if   ( grade  ==   null )
             this . grade  =   "" ;
         else
             this . grade  =  grade ;
     }

     /**
     * Constructs the course with the specified information, with no grade
     * established.
     * 
     *  @param  prefix the prefix of the course designation
     *  @param  number the number of the course designation
     *  @param  title the title of the course
     */
     public   Course ( String  prefix ,   int  number ,   String  title )
     {
         this ( prefix ,  number ,  title ,   "" );
     }

     /**
     * Returns the prefix of the course designation.
     * 
     *  @return  the prefix of the course designation
     */
     public   String  getPrefix ()
     {
         return  prefix ;
     }

     /**
     * Returns the number of the course designation.
     * 
     *  @return  the number of the course designation
     */
     public   int  getNumber ()
     {
         return  number ;
     }

     /**
     * Returns the title of this course.
     * 
     *  @return  the prefix of the course
     */
     public   String  getTitle ()
     {
         return  title ;
     }

     /**
     * Returns the grade for this course.
     * 
     *  @return  the grade for this course
     */
     public   String  getGrade ()
     {
         return  grade ;
     }

     /**
     * Sets the grade for this course to the one specified.
     * 
     *  @param  grade the new grade for the course
     */
     public   void  setGrade ( String  grade )
     {
         this . grade  =  grade ;
     }

     /**
     * Returns true if this course has been taken (if a grade has been received).
     * 
     *  @return  true if this course has been taken and false otherwise
     */
     public   boolean  taken ()
     {
         return   ! grade . equals ( "" );
     }

     /**
     * Determines if this course is equal to the one specified, based on the
     * course designation (prefix and number).
     * 
     *  @return  true if this course is equal to the parameter
     */
     public   boolean  equals ( Object  other )
     {
         boolean  result  =   false ;
         if   ( other  instanceof   Course )
         {
             Course  otherCourse  =   ( Course )  other ;
             if   ( prefix . equals ( otherCourse . getPrefix ())   &&
                    number  ==  otherCourse . getNumber ())
                result  =   true ;
         }
         return  result ;
     }

     /**
     * Creates and returns a string representation of this course.
     * 
     *  @return  a string representation of the course
     */
     public   String  toString ()
     {
         String  result  =  prefix  +   " "   +  number  +   ": "   +  title ;
         if   ( ! grade . equals ( "" ))
            result  +=   "  ["   +  grade  +   "]" ;
         return  result ;
     }
}

Chap15/POSTester/POSTester.java

Chap15/POSTester/POSTester.java

import  java . io . IOException ;

/**
 * Demonstrates the use of a list to manage a set of objects.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   POSTester
{
     /**
     * Creates and populates a Program of Study. Then saves it using serialization.
     */
     public   static   void  main ( String []  args )   throws   IOException
     {
         ProgramOfStudy  pos  =   new   ProgramOfStudy ();

        pos . addCourse ( new   Course ( "CS" ,   101 ,   "Introduction to Programming" ,   "A-" ));
        pos . addCourse ( new   Course ( "ARCH" ,   305 ,   "Building Analysis" ,   "A" ));
        pos . addCourse ( new   Course ( "GER" ,   210 ,   "Intermediate German" ));
        pos . addCourse ( new   Course ( "CS" ,   320 ,   "Computer Architecture" ));
        pos . addCourse ( new   Course ( "THE" ,   201 ,   "The Theatre Experience" ));

         Course  arch  =  pos . find ( "CS" ,   320 );
        pos . addCourseAfter ( arch ,   new   Course ( "CS" ,   321 ,   "Operating Systems" ));

         Course  theatre  =  pos . find ( "THE" ,   201 );
        theatre . setGrade ( "A-" );

         Course  german  =  pos . find ( "GER" ,   210 );
        pos . replace ( german ,   new   Course ( "FRE" ,   110 ,   "Beginning French" ,   "B+" ));

         System . out . println ( pos );

        pos . save ( "ProgramOfStudy" );      
     }
}

Chap15/POSTester/ProgramOfStudy

Chap15/POSTester/ProgramOfStudy.java

Chap15/POSTester/ProgramOfStudy.java

import  java . io . FileInputStream ;
import  java . io . FileOutputStream ;
import  java . io . IOException ;
import  java . io . ObjectInputStream ;
import  java . io . ObjectOutputStream ;
import  java . io . Serializable ;
import  java . util . Iterator ;
import  java . util . LinkedList ;
import  java . util . List ;

/**
 * Represents a Program of Study, a list of courses taken and planned, for an
 * individual student.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ProgramOfStudy   implements   Iterable < Course > ,   Serializable
{
     private   List < Course >  list ;

     /**
     * Constructs an initially empty Program of Study.
     */
     public   ProgramOfStudy ()
     {
        list  =   new   LinkedList < Course > ();
     }

     /**
     * Adds the specified course to the end of the course list.
     * 
     *  @param  course the course to add
     */
     public   void  addCourse ( Course  course )
     {
         if   ( course  !=   null )
            list . add ( course );
     }

     /**
     * Finds and returns the course matching the specified prefix and number.
     * 
     *  @param  prefix the prefix of the target course
     *  @param  number the number of the target course
     *  @return  the course, or null if not found
     */
     public   Course  find ( String  prefix ,   int  number )
     {
         for   ( Course  course  :  list )
             if   ( prefix . equals ( course . getPrefix ())   &&
                    number  ==  course . getNumber ())
                 return  course ;

         return   null ;
     }

     /**
     * Adds the specified course after the target course. Does nothing if
     * either course is null or if the target is not found.
     * 
     *  @param  target the course after which the new course will be added
     *  @param  newCourse the course to add
     */
     public   void  addCourseAfter ( Course  target ,   Course  newCourse )
     {
         if   ( target  ==   null   ||  newCourse  ==   null )
             return ;

         int  targetIndex  =  list . indexOf ( target );
         if   ( targetIndex  !=   - 1 )
            list . add ( targetIndex  +   1 ,  newCourse );
     }

     /**
     * Replaces the specified target course with the new course. Does nothing if
     * either course is null or if the target is not found.
     * 
     *  @param  target the course to be replaced
     *  @param  newCourse the new course to add
     */
     public   void  replace ( Course  target ,   Course  newCourse )
     {
         if   ( target  ==   null   ||  newCourse  ==   null )
             return ;

         int  targetIndex  =  list . indexOf ( target );
         if   ( targetIndex  !=   - 1 )
            list . set ( targetIndex ,  newCourse );
     }

     /**
     * Creates and returns a string representation of this Program of Study.
     * 
     *  @return  a string representation of the Program of Study
     */
     public   String  toString ()
     {
         String  result  =   "" ;
         for   ( Course  course  :  list )
            result  +=  course  +   "\n" ;
         return  result ;
     }

     /**
     * Returns an iterator for this Program of Study.
     * 
     *  @return  an iterator for the Program of Study
     */
     public   Iterator < Course >  iterator ()
     {
         return  list . iterator ();
     }

     /**
     * Saves a serialized version of this Program of Study to the specified
     * file name.
     * 
     *  @param  fileName the file name under which the POS will be stored
     *  @throws  IOException
     */
     public   void  save ( String  fileName )   throws   IOException
     {
         FileOutputStream  fos  =   new   FileOutputStream ( fileName );  
         ObjectOutputStream  oos  =   new   ObjectOutputStream ( fos );  
        oos . writeObject ( this );  
        oos . flush ();  
        oos . close ();  
     }

     /**
     * Loads a serialized Program of Study from the specified file.
     * 
     *  @param  fileName the file from which the POS is read
     *  @return  the loaded Program of Study
     *  @throws  IOException
     *  @throws  ClassNotFoundException
     */
     public   static   ProgramOfStudy  load ( String  fileName )   throws   IOException ,   ClassNotFoundException
     {
         FileInputStream  fis  =   new   FileInputStream ( fileName );
         ObjectInputStream  ois  =   new   ObjectInputStream ( fis );
         ProgramOfStudy  pos  =   ( ProgramOfStudy )  ois . readObject ();
        ois . close ();

         return  pos ;
     }
}

Chap16/ArrayListIterator/jsjf/ArrayList.java

Chap16/ArrayListIterator/jsjf/ArrayList.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . * ;

/**
 * ArrayList represents an array implementation of a list. The front of
 * the list is kept at array index 0. This class will be extended
 * to create a specific kind of list.
 * 
 * Solution to Programming Project 15.8 (full implementation)
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   abstract   class   ArrayList < T >   implements   ListADT < T > ,   Iterable < T >
{
     private   final   static   int  DEFAULT_CAPACITY  =   100 ;
     private   final   static   int  NOT_FOUND  =   - 1 ;

     protected   int  rear ;
     protected  T []  list ;
     protected   int  modCount ;

     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayList ()
     {
         this ( DEFAULT_CAPACITY );
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the integer value of the size of the array list
     */
     public   ArrayList ( int  initialCapacity )
     {
        rear  =   0 ;
        list  =   ( T [])( new   Object [ initialCapacity ]);
        modCount  =   0 ;
     }

     /**
     * Creates a new array to store the contents of this list with
     * twice the capacity of the old one. Called by descendant classes
     * that add elements to the list.
     */
     protected   void  expandCapacity ()
     {
        list  =   Arrays . copyOf ( list ,  list . length  *   2 );   
     }

     /**
     * Removes and returns the last element in this list.
     *
     *  @return  the last element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeLast ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "ArrayList" );

        T result ;
        rear -- ;
        result  =  list [ rear ];
        list [ rear ]   =   null ;
        modCount ++ ;

         return  result ;
     }

     /**
     * Removes and returns the first element in this list.
     *
     *  @return  the first element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeFirst ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "ArrayList" );

        T result  =  list [ 0 ];
        rear -- ;
        
         // shift the elements
         for   ( int  scan  =   0 ;  scan  <  rear ;  scan ++ )
            list [ scan ]   =  list [ scan + 1 ];
 
        list [ rear ]   =   null ;
        modCount ++ ;
 
         return  result ;
     }

     /**
     * Removes and returns the specified element.
     *
     *  @param   element the element to be removed and returned from the list
     *  @return  the removed element
     *  @throws  ElementNotFoundException if the element is not in the list
     */
     public  T remove ( T element )
     {
        T result ;
         int  index  =  find ( element );

         if   ( index  ==  NOT_FOUND )
             throw   new   ElementNotFoundException ( "ArrayList" );

        result  =  list [ index ];
        rear -- ;

         // shift the appropriate elements 
         for   ( int  scan  =  index ;  scan  <  rear ;  scan ++ )
            list [ scan ]   =  list [ scan + 1 ];

        list [ rear ]   =   null ;
        modCount ++ ;

         return  result ;
     }

     /**
     * Returns a reference to the element at the front of this list.
     * The element is not removed from the list.  Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the first element in the list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "ArrayList" );  

         return  list [ 0 ];
     }

     /**
     * Returns a reference to the element at the rear of this list.
     * The element is not removed from the list. Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the last element of this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T last ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "ArrayList" );  

         return  list [ rear  -   1 ];
     }

     /**
     * Returns true if this list contains the specified element.
     *
     *  @param  target the target element
     *  @return  true if the target is in the list, false otherwise 
     */
     public   boolean  contains ( T target )
     {
         return   ( find ( target )   !=  NOT_FOUND );
     }

     /**
     * Returns the array index of the specified element, or the
     * constant NOT_FOUND if it is not found.
     *
     *  @param  target the target element
     *  @return  the index of the target element, or the 
     *         NOT_FOUND constant
     */
     private   int  find ( T target )
     {
         int  scan  =   0 ;  
         int  result  =  NOT_FOUND ;

         if   ( ! isEmpty ())
             while   ( result  ==  NOT_FOUND  &&  scan  <  rear )
                 if   ( target . equals ( list [ scan ]))
                    result  =  scan ;
                 else
                    scan ++ ;

         return  result ;
     }

     /**
     * Returns true if this list is empty and false otherwise. 
     *
     *  @return  true if the list is empty, false otherwise
     */
     public   boolean  isEmpty ()
     {
         return   ( rear  ==   0 );
     }

     /**
     * Returns the number of elements currently in this list.
     *
     *  @return  the number of elements in the list
     */
     public   int  size ()
     {
         return  rear ;
     }

     /**
     * Returns a string representation of this list. 
     * 
     *  @return  the string representation of the list
     */
     public   String  toString ()
     {
         String  result  =   "" ;

         for   ( int  scan = 0 ;  scan  <  rear ;  scan ++ )  
            result  =  result  +  list [ scan ]   +   "\n" ;

         return  result ;
     }

     /**
     * Returns an iterator for the elements currently in this list.
     * 
     *  @return  an iterator for the elements in the list
     */
     public   Iterator < T >  iterator ()
     {
         return   new   ArrayListIterator ();
     }

     /**
     * ArrayListIterator iterator over the elements of an ArrayList.
     */  
     private   class   ArrayListIterator   implements   Iterator < T >
     {
         int  iteratorModCount ;
         int  current ;

         /**
         * Sets up this iterator using the specified modCount.
         * 
         *  @param  modCount the current modification count for the ArrayList
         */
         public   ArrayListIterator ()
         {
            iteratorModCount  =  modCount ;
            current  =   0 ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( iteratorModCount  !=  modCount )
                 throw   new   ConcurrentModificationException ();

             return   ( current  <  rear );
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return   the next element in the iteration
         *  @throws   NoSuchElementException if an element not found exception occurs
         *  @throws   ConcurrentModificationException if the collection has changed
         */
         public  T next ()   throws   ConcurrentModificationException
         {
             if   ( ! hasNext ())
                 throw   new   NoSuchElementException ();

            current ++ ;

             return  list [ current  -   1 ];
         }

         /**
         * The remove operation is not supported in this collection.
         * 
         *  @throws  UnsupportedOperationException if the remove method is called
         */
         public   void  remove ()   throws   UnsupportedOperationException
         {
             throw   new   UnsupportedOperationException ();
         }

     }    
}

Chap16/ArrayListIterator/jsjf/ArrayOrderedList.java

Chap16/ArrayListIterator/jsjf/ArrayOrderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayOrderedList represents an array implementation of an ordered list.
 * 
 * Solution to Programming Project 15.9 (full implementation)
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayOrderedList < T >   extends   ArrayList < T >
implements   OrderedListADT < T >
{
     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayOrderedList ()
     {
         super ();
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the initial size of the list
     */
     public   ArrayOrderedList ( int  initialCapacity )
     {
         super ( initialCapacity );
     }

     /**
     * Adds the specified Comparable element to this list, keeping
     * the elements in sorted order.
     *
     *  @param  element the element to be added to the list
     */
     public   void  add ( T element )
     {
         if   ( ! ( element  instanceof   Comparable ))
             throw   new   NonComparableElementException ( "OrderedList" );

         Comparable < T >  comparableElement  =   ( Comparable < T > ) element ;

         if   ( size ()   ==  list . length )
            expandCapacity ();

         int  scan  =   0 ;   

         // find the insertion location
         while   ( scan  <  rear  &&  comparableElement . compareTo ( list [ scan ])   >   0 )
            scan ++ ;

         // shift existing elements up one
         for   ( int  shift  =  rear ;  shift  >  scan ;  shift -- )
            list [ shift ]   =  list [ shift  -   1 ];

         // insert element
        list [ scan ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }
}

Chap16/ArrayListIterator/jsjf/ArrayUnorderedList.java

Chap16/ArrayListIterator/jsjf/ArrayUnorderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayUnorderedList represents an array implementation of an unordered list.
 * 
 * Solution to Programming Project 15.10 (full implementation)
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayUnorderedList < T >   extends   ArrayList < T >  
implements   UnorderedListADT < T >
{
     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayUnorderedList ()
     {
         super ();
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the initial size of the list
     */
     public   ArrayUnorderedList ( int  initialCapacity )
     {
         super ( initialCapacity );
     }

     /**
     * Adds the specified element to the front of this list.
     * 
     *  @param  element the element to be added to the front of the list
     */
     public   void  addToFront ( T element )
     {
         if   ( size ()   ==  list . length )
            expandCapacity ();

         // shift elements up one 
         for   ( int  scan  =  rear ;  scan  >   0 ;  scan -- )
            list [ scan ]   =  list [ scan  -   1 ];

        list [ 0 ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }

     /**
     * Adds the specified element to the rear of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToRear ( T element )
     {
         if   ( size ()   ==  list . length )
            expandCapacity ();

        list [ rear ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }

     /**
     * Adds the specified element after the specified target element.
     * Throws an ElementNotFoundException if the target is not found.
     *
     *  @param  element the element to be added after the target element
     *  @param  target  the target that the element is to be added after
     */
     public   void  addAfter ( T element ,  T target )
     {
         if   ( size ()   ==  list . length )
            expandCapacity ();

         int  scan  =   0 ;

         // find the insertion point
         while   ( scan  <  rear  &&   ! target . equals ( list [ scan ]))  
            scan ++ ;

         if   ( scan  ==  rear )
             throw   new   ElementNotFoundException ( "UnorderedList" );

        scan ++ ;

         // shift elements up one
         for   ( int  shift  =  rear ;  shift  >  scan ;  shift -- )
            list [ shift ]   =  list [ shift  -   1 ];

         // insert element
        list [ scan ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }
}

Chap16/ArrayListIterator/jsjf/exceptions/ElementNotFoundException.java

Chap16/ArrayListIterator/jsjf/exceptions/ElementNotFoundException.java

package  jsjf . exceptions ;

/**
 * ElementNotFoundException represents the situation in which a target element 
 * is not present in a collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ElementNotFoundException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     */
     public   ElementNotFoundException   ( String  collection )
     {
         super   ( "The target element is not in this "   +  collection );
     }
}

Chap16/ArrayListIterator/jsjf/exceptions/EmptyCollectionException.java

Chap16/ArrayListIterator/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException ( String  collection )
     {
         super ( "The "   +  collection  +   " is empty." );
     }
}

Chap16/ArrayListIterator/jsjf/exceptions/NonComparableElementException.java

Chap16/ArrayListIterator/jsjf/exceptions/NonComparableElementException.java

package  jsjf . exceptions ;

/**
 * NonComparableElementException  represents the situation in which an attempt 
 * is made to add an element that is not comparable to an ordered collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   NonComparableElementException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     * 
     *  @param  collection  the exception message to deliver
     */
     public   NonComparableElementException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " requires Comparable elements." );
     }
}

Chap16/ArrayListIterator/jsjf/ListADT.java

Chap16/ArrayListIterator/jsjf/ListADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * ListADT defines the interface to a general list collection. Specific
 * types of lists will extend this interface to complete the
 * set of necessary operations.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   ListADT < T >   extends   Iterable < T >
{
     /**  
     * Removes and returns the first element from this list. 
     * 
     *  @return  the first element from this list
     */
     public  T removeFirst ();

     /**  
     * Removes and returns the last element from this list. 
     *
     *  @return  the last element from this list
     */
     public  T removeLast ();

     /**  
     * Removes and returns the specified element from this list. 
     *
     *  @param  element the element to be removed from the list
     */
     public  T remove ( T element );

     /**  
     * Returns a reference to the first element in this list. 
     *
     *  @return  a reference to the first element in this list
     */
     public  T first ();

     /**  
     * Returns a reference to the last element in this list. 
     *
     *  @return  a reference to the last element in this list
     */
     public  T last ();

     /**  
     * Returns true if this list contains the specified target element. 
     *
     *  @param  target the target that is being sought in the list
     *  @return  true if the list contains this element
     */
     public   boolean  contains ( T target );

     /**  
     * Returns true if this list contains no elements. 
     *
     *  @return  true if this list contains no elements
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this list. 
     *
     *  @return  the integer representation of number of elements in this list
     */
     public   int  size ();

     /**  
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements in this list
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns a string representation of this list. 
     *
     *  @return  a string representation of this list
     */
     public   String  toString ();
}

Chap16/ArrayListIterator/jsjf/OrderedListADT.java

Chap16/ArrayListIterator/jsjf/OrderedListADT.java

package  jsjf ;

/**
 * OrderedListADT defines the interface to an ordered list collection. Only
 * Comparable elements are stored, kept in the order determined by
 * the inherent relationship among the elements.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   OrderedListADT < T >   extends   ListADT < T >
{
     /**
     * Adds the specified element to this list at the proper location
     *
     *  @param  element the element to be added to this list
     */
     public   void  add ( T element );
}

Chap16/ArrayListIterator/jsjf/UnorderedListADT.java

Chap16/ArrayListIterator/jsjf/UnorderedListADT.java

package  jsjf ;

/**
 * UnorderedListADT defines the interface to an unordered list collection. 
 * Elements are stored in any order the user desires.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   UnorderedListADT < T >   extends   ListADT < T >
{
     /**  
     * Adds the specified element to the front of this list. 
     *
     *  @param  element the element to be added to the front of this list    
     */
     public   void  addToFront ( T element );   

     /**  
     * Adds the specified element to the rear of this list. 
     *
     *  @param  element the element to be added to the rear of this list    
     */
     public   void  addToRear ( T element );  

     /**  
     * Adds the specified element after the specified target. 
     *
     *  @param  element the element to be added after the target
     *  @param  target  the target is the item that the element will be added
     *                after    
     */
     public   void  addAfter ( T element ,  T target );
}

Chap16/LinkedListIterator/jsjf/exceptions/ElementNotFoundException.java

Chap16/LinkedListIterator/jsjf/exceptions/ElementNotFoundException.java

package  jsjf . exceptions ;

/**
 * ElementNotFoundException represents the situation in which a target element 
 * is not present in a collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ElementNotFoundException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     */
     public   ElementNotFoundException   ( String  collection )
     {
         super   ( "The target element is not in this "   +  collection );
     }
}

Chap16/LinkedListIterator/jsjf/exceptions/EmptyCollectionException.java

Chap16/LinkedListIterator/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException ( String  collection )
     {
         super ( "The "   +  collection  +   " is empty." );
     }
}

Chap16/LinkedListIterator/jsjf/exceptions/NonComparableElementException.java

Chap16/LinkedListIterator/jsjf/exceptions/NonComparableElementException.java

package  jsjf . exceptions ;

/**
 * NonComparableElementException  represents the situation in which an attempt 
 * is made to add an element that is not comparable to an ordered collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   NonComparableElementException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     * 
     *  @param  collection  the exception message to deliver
     */
     public   NonComparableElementException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " requires Comparable elements." );
     }
}

Chap16/LinkedListIterator/jsjf/LinearNode.java

Chap16/LinkedListIterator/jsjf/LinearNode.java

package  jsjf ;

/**
 * LinearNode represents a node in a linked list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinearNode < E >
{
     private   LinearNode < E >  next ;
     private  E element ;

     /**
     * Creates an empty node.
     */
     public   LinearNode ()
     {
        next  =   null ;
        element  =   null ;
     }

     /**
     * Creates a node storing the specified element.
     *
     *  @param  elem the element to be stored within the new node
     */
     public   LinearNode ( E elem )
     {
        next  =   null ;
        element  =  elem ;
     }

     /**
     * Returns the node that follows this one.
     *
     *  @return  the node that follows the current one
     */
     public   LinearNode < E >  getNext ()
     {
         return  next ;
     }

     /**
     * Sets the node that follows this one.
     *
     *  @param  node the node to be set to follow the current one
     */
     public   void  setNext ( LinearNode < E >  node )
     {
        next  =  node ;
     }

     /**
     * Returns the element stored in this node.
     *
     *  @return  the element stored in this node
     */
     public  E getElement ()
     {
         return  element ;
     }

     /**
     * Sets the element stored in this node.
     *
     *  @param  elem the element to be stored in this node
     */
     public   void  setElement ( E elem )
     {
        element  =  elem ;
     }
}

Chap16/LinkedListIterator/jsjf/LinkedList.java

Chap16/LinkedListIterator/jsjf/LinkedList.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . * ;

/**
 * LinkedList represents a linked implementation of a list.
 * 
 * Solution to Programming Project 15.11 (full implementation)
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   abstract   class   LinkedList < T >   implements   ListADT < T > ,   Iterable < T >
{
     protected   int  count ;
     protected   LinearNode < T >  head ,  tail ;
     protected   int  modCount ;

     /**
     * Creates an empty list.
     */
     public   LinkedList ()
     {
        count  =   0 ;
        head  =  tail  =   null ;
        modCount  =   0 ;
     }

     /**
     * Removes the first element in this list and returns a reference
     * to it. Throws an EmptyCollectionException if the list is empty.
     *
     *  @return  a reference to the first element of this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T removeFirst ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "LinkedList" );
      
         LinearNode < T >  result  =  head ;  
        head  =  head . getNext ();
         if   ( head  ==   null )
            tail  =   null ;
        count -- ;
        modCount ++ ;
      
         return  result . getElement ();
     }

     /**
     * Removes the last element in this list and returns a reference
     * to it. Throws an EmptyCollectionException if the list is empty.
     *
     *  @return  the last element in this list
     *  @throws  EmptyCollectionException if the list is empty    
     */
     public  T removeLast ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "LinkedList" );

         LinearNode < T >  previous  =   null ;
         LinearNode < T >  current  =  head ;

         while   ( current . getNext ()   !=   null )
         {
            previous  =  current ;  
            current  =  current . getNext ();
         }
      
         LinearNode < T >  result  =  tail ;  
        tail  =  previous ;
         if   ( tail  ==   null )    // only one element in list
            head  =   null ;
         else
            tail . setNext ( null );
        count -- ;
        modCount ++ ;
      
         return  result . getElement ();
     }

     /**
     * Removes the first instance of the specified element from this
     * list and returns a reference to it. Throws an EmptyCollectionException 
     * if the list is empty. Throws a ElementNotFoundException if the 
     * specified element is not found in the list.
     *
     *  @param   targetElement the element to be removed from the list
     *  @return  a reference to the removed element
     *  @throws  EmptyCollectionException if the list is empty
     *  @throws  ElementNotFoundException if the target element is not found
     */
     public  T remove ( T targetElement )   throws   EmptyCollectionException ,  
     ElementNotFoundException  
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "LinkedList" );

         boolean  found  =   false ;
         LinearNode < T >  previous  =   null ;
         LinearNode < T >  current  =  head ;

         while   ( current  !=   null   &&   ! found )
             if   ( targetElement . equals ( current . getElement ()))
                found  =   true ;
             else
             {
                previous  =  current ;
                current  =  current . getNext ();
             }

         if   ( ! found )
             throw   new   ElementNotFoundException ( "LinkedList" );

         if   ( size ()   ==   1 )    // only one element in the list
            head  =  tail  =   null ;
         else   if   ( current . equals ( head ))    // target is at the head 
            head  =  current . getNext ();
         else   if   ( current . equals ( tail ))    // target is at the tail
         {
            tail  =  previous ;
            tail . setNext ( null );
         }
         else    // target is in the middle
            previous . setNext ( current . getNext ());

        count -- ;
        modCount ++ ;

         return  current . getElement ();
     }

     /**
     * Returns the first element in this list without removing it. 
     *
     *  @return  the first element in this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "LinkedList" );
        
         return  head . getElement ();
     }

     /**
     * Returns the last element in this list without removing it. 
     *
     *  @return  the last element in this list  
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T last ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "LinkedList" );
        
         return  tail . getElement ();
     }

     /**
     * Returns true if the specified element is found in this list and 
     * false otherwise. Throws an EmptyCollectionException if the list 
     * is empty.
     *
     *  @param   targetElement the element that is sought in the list
     *  @return  true if the element is found in this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public   boolean  contains ( T targetElement )   throws   EmptyCollectionException  
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "LinkedList" );

         boolean  found  =   false ;
         LinearNode < T >  current  =  head ;

         while   ( current  !=   null   &&   ! found )  
             if   ( targetElement . equals ( current . getElement ()))
                found  =   true ;
             else
                current  =  current . getNext ();
      
         return  found ;
     }

     /**
     * Returns true if this list is empty and false otherwise.
     *
     *  @return  true if the list is empty, false otherwise
     */
     public   boolean  isEmpty ()
     {
         return   ( count  ==   0 );
     }

     /**
     * Returns the number of elements in this list.
     *
     *  @return  the number of elements in the list
     */
     public   int  size ()
     {
         return  count ;
     }

     /**
     * Returns a string representation of this list.
     *
     *  @return  a string representation of the list    
     */
     public   String  toString ()
     {
         LinearNode < T >  current  =  head ;
         String  result  =   "" ;

         while   ( current  !=   null )
         {
            result  =  result  +  current . getElement ()   +   "\n" ;
            current  =  current . getNext ();
         }

         return  result ;
     }

     /**
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements of the list
     */
     public   Iterator < T >  iterator ()
     {
         return   new   LinkedListIterator ();
     }

     /**
     * LinkedIterator represents an iterator for a linked list of linear nodes.
     */
     private   class   LinkedListIterator   implements   Iterator < T >
     {
         private   int  iteratorModCount ;    // the number of elements in the collection
         private   LinearNode < T >  current ;    // the current position

         /**
         * Sets up this iterator using the specified items.
         *
         *  @param  collection  the collection the iterator will move over
         *  @param  size        the integer size of the collection
         */
         public   LinkedListIterator ()
         {
            current  =  head ;
            iteratorModCount  =  modCount ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( iteratorModCount  !=  modCount )  
                 throw   new   ConcurrentModificationException ();

             return   ( current  !=   null );
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return  the next element in the iteration
         *  @throws  NoSuchElementException if the iterator is empty
         */
         public  T next ()   throws   ConcurrentModificationException
         {
             if   ( ! hasNext ())
                 throw   new   NoSuchElementException ();

            T result  =  current . getElement ();
            current  =  current . getNext ();
             return  result ;
         }

         /**
         * The remove operation is not supported.
         * 
         *  @throws  UnsupportedOperationException if the remove operation is called
         */
         public   void  remove ()   throws   UnsupportedOperationException
         {
             throw   new   UnsupportedOperationException ();
         }
     }

}


Chap16/LinkedListIterator/jsjf/LinkedOrderedList.java

Chap16/LinkedListIterator/jsjf/LinkedOrderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * LinkedOrderedList represents a singly linked implementation of an 
 * ordered list.
 * 
 * Solution to Programming Project 15.12 (full implementation)
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinkedOrderedList < T >   extends   LinkedList < T >  
implements   OrderedListADT < T >
{
     /**
     * Creates an empty list.
     */
     public   LinkedOrderedList ()
     {
         super ();
     }

     /**
     * Adds the specified element to this list at the location determined by
     * the element's natural ordering. Throws a NonComparableElementException 
     * if the element is not comparable.
     *
     *  @param  element the element to be added to this list
     *  @throws  NonComparableElementException if the element is not comparable
     */
     public   void  add ( T element )
     {
         if   ( ! ( element  instanceof   Comparable ))
             throw   new   NonComparableElementException ( "LinkedOrderedList" );
        
         Comparable < T >  comparableElement  =   ( Comparable < T > ) element ;

         LinearNode < T >  current  =  head ;
         LinearNode < T >  previous  =   null ;
         LinearNode < T >  newNode   =   new   LinearNode < T > ( element );
      
         if   ( isEmpty ())    // list is empty
         {
            head  =  newNode ;
            tail  =  newNode ;
         }
         else   if   ( comparableElement . compareTo ( head . getElement ())   <=   0 )   
             // element goes in front
         {
            newNode . setNext ( head );
            head  =  newNode ;
         }
         else   if   ( comparableElement . compareTo ( tail . getElement ())   >=   0 )   
             // element goes at tail
         {
            tail . setNext ( newNode );
            tail  =  newNode ;
         }
         else    // element goes in the middle
         {
             while   (( comparableElement . compareTo ( current . getElement ())   >   0 ))
             {
                previous  =  current ;
                current  =  current . getNext ();
             }
         
            newNode . setNext ( current );
            previous . setNext ( newNode );
         }
      
        count ++ ;
        modCount ++ ;
     }
}

Chap16/LinkedListIterator/jsjf/LinkedUnorderedList.java

Chap16/LinkedListIterator/jsjf/LinkedUnorderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * LinkedUnorderedList represents a singly linked implementation of an 
 * unordered list.
 * 
 * Solution to Programming Project 15.13 (full implementation)
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinkedUnorderedList < T >   extends   LinkedList < T >  
implements   UnorderedListADT < T >
{
     /**
     * Creates an empty list.
     */
     public   LinkedUnorderedList ()
     {
         super ();
     }

     /**
     * Adds the specified element to the front of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToFront ( T element )
     {
         LinearNode < T >  newNode   =   new   LinearNode < T > ( element );
        
         if   ( isEmpty ())
         {
            head  =  newNode ;
            tail  =  newNode ;
         }
         else  
         {
            newNode . setNext ( head );
            head  =  newNode ;
         }
      
        count ++ ;
        modCount ++ ;
     }

     /**
     * Adds the specified element to the rear of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToRear ( T element )
     {
         LinearNode < T >  newNode   =   new   LinearNode < T > ( element );
        
         if   ( isEmpty ())
         {
            head  =  newNode ;
            tail  =  newNode ;
         }
         else  
         {
            tail . setNext ( newNode );
            tail  =  newNode ;
         }
                
        count ++ ;
        modCount ++ ;
     }


     /**
     * Adds the specified element to this list after the given target.
     *
     *  @param   element the element to be added to this list
     *  @param   target the target element to be added after
     *  @throws  ElementNotFoundException if the target is not found
     */
     public   void  addAfter ( T element ,  T target )
     {
         if   ( isEmpty ())
             throw   new   ElementNotFoundException ( "LinkedUnorderedList" );
        
         boolean  found  =   false ;
         LinearNode < T >  current  =  head ;
         LinearNode < T >  newNode  =   new   LinearNode < T > ( element );
        
         while   ( current  !=   null   &&   ! found )  
             if   ( target . equals ( current . getElement ()))
                found  =   true ;
             else
                current  =  current . getNext ();     
        
         if   ( ! found )
             throw   new   ElementNotFoundException ( "LinkedUnorderedList" );
        
        newNode . setNext ( current . getNext ());
        current . setNext ( newNode );
        
        count ++ ;
        modCount ++ ;
     }    
}

Chap16/LinkedListIterator/jsjf/ListADT.java

Chap16/LinkedListIterator/jsjf/ListADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * ListADT defines the interface to a general list collection. Specific
 * types of lists will extend this interface to complete the
 * set of necessary operations.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   ListADT < T >   extends   Iterable < T >
{
     /**  
     * Removes and returns the first element from this list. 
     * 
     *  @return  the first element from this list
     */
     public  T removeFirst ();

     /**  
     * Removes and returns the last element from this list. 
     *
     *  @return  the last element from this list
     */
     public  T removeLast ();

     /**  
     * Removes and returns the specified element from this list. 
     *
     *  @param  element the element to be removed from the list
     */
     public  T remove ( T element );

     /**  
     * Returns a reference to the first element in this list. 
     *
     *  @return  a reference to the first element in this list
     */
     public  T first ();

     /**  
     * Returns a reference to the last element in this list. 
     *
     *  @return  a reference to the last element in this list
     */
     public  T last ();

     /**  
     * Returns true if this list contains the specified target element. 
     *
     *  @param  target the target that is being sought in the list
     *  @return  true if the list contains this element
     */
     public   boolean  contains ( T target );

     /**  
     * Returns true if this list contains no elements. 
     *
     *  @return  true if this list contains no elements
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this list. 
     *
     *  @return  the integer representation of number of elements in this list
     */
     public   int  size ();

     /**  
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements in this list
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns a string representation of this list. 
     *
     *  @return  a string representation of this list
     */
     public   String  toString ();
}

Chap16/LinkedListIterator/jsjf/OrderedListADT.java

Chap16/LinkedListIterator/jsjf/OrderedListADT.java

package  jsjf ;

/**
 * OrderedListADT defines the interface to an ordered list collection. Only
 * Comparable elements are stored, kept in the order determined by
 * the inherent relationship among the elements.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   OrderedListADT < T >   extends   ListADT < T >
{
     /**
     * Adds the specified element to this list at the proper location
     *
     *  @param  element the element to be added to this list
     */
     public   void  add ( T element );
}

Chap16/LinkedListIterator/jsjf/UnorderedListADT.java

Chap16/LinkedListIterator/jsjf/UnorderedListADT.java

package  jsjf ;

/**
 * UnorderedListADT defines the interface to an unordered list collection. 
 * Elements are stored in any order the user desires.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   UnorderedListADT < T >   extends   ListADT < T >
{
     /**  
     * Adds the specified element to the front of this list. 
     *
     *  @param  element the element to be added to the front of this list    
     */
     public   void  addToFront ( T element );   

     /**  
     * Adds the specified element to the rear of this list. 
     *
     *  @param  element the element to be added to the rear of this list    
     */
     public   void  addToRear ( T element );  

     /**  
     * Adds the specified element after the specified target. 
     *
     *  @param  element the element to be added after the target
     *  @param  target  the target is the item that the element will be added
     *                after    
     */
     public   void  addAfter ( T element ,  T target );
}

Chap16/POSClear/Course.java

Chap16/POSClear/Course.java

import  java . io . Serializable ;

/**
 * Represents a course that might be taken by a student.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   Course   implements   Serializable
{
     private   String  prefix ;
     private   int  number ;
     private   String  title ;
     private   String  grade ;

     /**
     * Constructs the course with the specified information.
     * 
     *  @param  prefix the prefix of the course designation
     *  @param  number the number of the course designation
     *  @param  title the title of the course
     *  @param  grade the grade received for the course
     */
     public   Course ( String  prefix ,   int  number ,   String  title ,   String  grade )
     {
         this . prefix  =  prefix ;
         this . number  =  number ;
         this . title  =  title ;
         if   ( grade  ==   null )
             this . grade  =   "" ;
         else
             this . grade  =  grade ;
     }

     /**
     * Constructs the course with the specified information, with no grade
     * established.
     * 
     *  @param  prefix the prefix of the course designation
     *  @param  number the number of the course designation
     *  @param  title the title of the course
     */
     public   Course ( String  prefix ,   int  number ,   String  title )
     {
         this ( prefix ,  number ,  title ,   "" );
     }

     /**
     * Returns the prefix of the course designation.
     * 
     *  @return  the prefix of the course designation
     */
     public   String  getPrefix ()
     {
         return  prefix ;
     }

     /**
     * Returns the number of the course designation.
     * 
     *  @return  the number of the course designation
     */
     public   int  getNumber ()
     {
         return  number ;
     }

     /**
     * Returns the title of this course.
     * 
     *  @return  the prefix of the course
     */
     public   String  getTitle ()
     {
         return  title ;
     }

     /**
     * Returns the grade for this course.
     * 
     *  @return  the grade for this course
     */
     public   String  getGrade ()
     {
         return  grade ;
     }

     /**
     * Sets the grade for this course to the one specified.
     * 
     *  @param  grade the new grade for the course
     */
     public   void  setGrade ( String  grade )
     {
         this . grade  =  grade ;
     }

     /**
     * Returns true if this course has been taken (if a grade has been received).
     * 
     *  @return  true if this course has been taken and false otherwise
     */
     public   boolean  taken ()
     {
         return   ! grade . equals ( "" );
     }

     /**
     * Determines if this course is equal to the one specified, based on the
     * course designation (prefix and number).
     * 
     *  @return  true if this course is equal to the parameter
     */
     public   boolean  equals ( Object  other )
     {
         boolean  result  =   false ;
         if   ( other  instanceof   Course )
         {
             Course  otherCourse  =   ( Course )  other ;
             if   ( prefix . equals ( otherCourse . getPrefix ())   &&
                    number  ==  otherCourse . getNumber ())
                result  =   true ;
         }
         return  result ;
     }

     /**
     * Creates and returns a string representation of this course.
     * 
     *  @return  a string representation of the course
     */
     public   String  toString ()
     {
         String  result  =  prefix  +   " "   +  number  +   ": "   +  title ;
         if   ( ! grade . equals ( "" ))
            result  +=   "  ["   +  grade  +   "]" ;
         return  result ;
     }
}

Chap16/POSClear/POSClear.java

Chap16/POSClear/POSClear.java

import  java . util . Iterator ;

/**
 * Demonstrates the use of an explicit iterator.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   POSClear
{
     /**
     * Reads a serialized Program of Study, then removes all courses that
     * don't have a grade.
     */
     public   static   void  main ( String []  args )   throws   Exception
     {
         ProgramOfStudy  pos  =   ProgramOfStudy . load ( "ProgramOfStudy" );

         System . out . println ( pos );

         System . out . println ( "Removing courses with no grades.\n" );

         Iterator < Course >  itr  =  pos . iterator ();
         while   ( itr . hasNext ())
         {
             Course  course  =  itr . next ();
             if   ( ! course . taken ())
                itr . remove ();
         }

         System . out . println ( pos );

        pos . save ( "ProgramOfStudy" );
     }
}

Chap16/POSClear/ProgramOfStudy

Chap16/POSClear/ProgramOfStudy.java

Chap16/POSClear/ProgramOfStudy.java

import  java . io . FileInputStream ;
import  java . io . FileOutputStream ;
import  java . io . IOException ;
import  java . io . ObjectInputStream ;
import  java . io . ObjectOutputStream ;
import  java . io . Serializable ;
import  java . util . Iterator ;
import  java . util . LinkedList ;
import  java . util . List ;

/**
 * Represents a Program of Study, a list of courses taken and planned, for an
 * individual student.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ProgramOfStudy   implements   Iterable < Course > ,   Serializable
{
     private   List < Course >  list ;

     /**
     * Constructs an initially empty Program of Study.
     */
     public   ProgramOfStudy ()
     {
        list  =   new   LinkedList < Course > ();
     }

     /**
     * Adds the specified course to the end of the course list.
     * 
     *  @param  course the course to add
     */
     public   void  addCourse ( Course  course )
     {
         if   ( course  !=   null )
            list . add ( course );
     }

     /**
     * Finds and returns the course matching the specified prefix and number.
     * 
     *  @param  prefix the prefix of the target course
     *  @param  number the number of the target course
     *  @return  the course, or null if not found
     */
     public   Course  find ( String  prefix ,   int  number )
     {
         for   ( Course  course  :  list )
             if   ( prefix . equals ( course . getPrefix ())   &&
                    number  ==  course . getNumber ())
                 return  course ;

         return   null ;
     }

     /**
     * Adds the specified course after the target course. Does nothing if
     * either course is null or if the target is not found.
     * 
     *  @param  target the course after which the new course will be added
     *  @param  newCourse the course to add
     */
     public   void  addCourseAfter ( Course  target ,   Course  newCourse )
     {
         if   ( target  ==   null   ||  newCourse  ==   null )
             return ;

         int  targetIndex  =  list . indexOf ( target );
         if   ( targetIndex  !=   - 1 )
            list . add ( targetIndex  +   1 ,  newCourse );
     }

     /**
     * Replaces the specified target course with the new course. Does nothing if
     * either course is null or if the target is not found.
     * 
     *  @param  target the course to be replaced
     *  @param  newCourse the new course to add
     */
     public   void  replace ( Course  target ,   Course  newCourse )
     {
         if   ( target  ==   null   ||  newCourse  ==   null )
             return ;

         int  targetIndex  =  list . indexOf ( target );
         if   ( targetIndex  !=   - 1 )
            list . set ( targetIndex ,  newCourse );
     }

     /**
     * Creates and returns a string representation of this Program of Study.
     * 
     *  @return  a string representation of the Program of Study
     */
     public   String  toString ()
     {
         String  result  =   "" ;
         for   ( Course  course  :  list )
            result  +=  course  +   "\n" ;
         return  result ;
     }

     /**
     * Returns an iterator for this Program of Study.
     * 
     *  @return  an iterator for the Program of Study
     */
     public   Iterator < Course >  iterator ()
     {
         return  list . iterator ();
     }

     /**
     * Saves a serialized version of this Program of Study to the specified
     * file name.
     * 
     *  @param  fileName the file name under which the POS will be stored
     *  @throws  IOException
     */
     public   void  save ( String  fileName )   throws   IOException
     {
         FileOutputStream  fos  =   new   FileOutputStream ( fileName );  
         ObjectOutputStream  oos  =   new   ObjectOutputStream ( fos );  
        oos . writeObject ( this );  
        oos . flush ();  
        oos . close ();  
     }

     /**
     * Loads a serialized Program of Study from the specified file.
     * 
     *  @param  fileName the file from which the POS is read
     *  @return  the loaded Program of Study
     *  @throws  IOException
     *  @throws  ClassNotFoundException
     */
     public   static   ProgramOfStudy  load ( String  fileName )   throws   IOException ,   ClassNotFoundException
     {
         FileInputStream  fis  =   new   FileInputStream ( fileName );
         ObjectInputStream  ois  =   new   ObjectInputStream ( fis );
         ProgramOfStudy  pos  =   ( ProgramOfStudy )  ois . readObject ();
        ois . close ();

         return  pos ;
     }
}

Chap16/POSGrades/Course.java

Chap16/POSGrades/Course.java

import  java . io . Serializable ;

/**
 * Represents a course that might be taken by a student.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   Course   implements   Serializable
{
     private   String  prefix ;
     private   int  number ;
     private   String  title ;
     private   String  grade ;

     /**
     * Constructs the course with the specified information.
     * 
     *  @param  prefix the prefix of the course designation
     *  @param  number the number of the course designation
     *  @param  title the title of the course
     *  @param  grade the grade received for the course
     */
     public   Course ( String  prefix ,   int  number ,   String  title ,   String  grade )
     {
         this . prefix  =  prefix ;
         this . number  =  number ;
         this . title  =  title ;
         if   ( grade  ==   null )
             this . grade  =   "" ;
         else
             this . grade  =  grade ;
     }

     /**
     * Constructs the course with the specified information, with no grade
     * established.
     * 
     *  @param  prefix the prefix of the course designation
     *  @param  number the number of the course designation
     *  @param  title the title of the course
     */
     public   Course ( String  prefix ,   int  number ,   String  title )
     {
         this ( prefix ,  number ,  title ,   "" );
     }

     /**
     * Returns the prefix of the course designation.
     * 
     *  @return  the prefix of the course designation
     */
     public   String  getPrefix ()
     {
         return  prefix ;
     }

     /**
     * Returns the number of the course designation.
     * 
     *  @return  the number of the course designation
     */
     public   int  getNumber ()
     {
         return  number ;
     }

     /**
     * Returns the title of this course.
     * 
     *  @return  the prefix of the course
     */
     public   String  getTitle ()
     {
         return  title ;
     }

     /**
     * Returns the grade for this course.
     * 
     *  @return  the grade for this course
     */
     public   String  getGrade ()
     {
         return  grade ;
     }

     /**
     * Sets the grade for this course to the one specified.
     * 
     *  @param  grade the new grade for the course
     */
     public   void  setGrade ( String  grade )
     {
         this . grade  =  grade ;
     }

     /**
     * Returns true if this course has been taken (if a grade has been received).
     * 
     *  @return  true if this course has been taken and false otherwise
     */
     public   boolean  taken ()
     {
         return   ! grade . equals ( "" );
     }

     /**
     * Determines if this course is equal to the one specified, based on the
     * course designation (prefix and number).
     * 
     *  @return  true if this course is equal to the parameter
     */
     public   boolean  equals ( Object  other )
     {
         boolean  result  =   false ;
         if   ( other  instanceof   Course )
         {
             Course  otherCourse  =   ( Course )  other ;
             if   ( prefix . equals ( otherCourse . getPrefix ())   &&
                    number  ==  otherCourse . getNumber ())
                result  =   true ;
         }
         return  result ;
     }

     /**
     * Creates and returns a string representation of this course.
     * 
     *  @return  a string representation of the course
     */
     public   String  toString ()
     {
         String  result  =  prefix  +   " "   +  number  +   ": "   +  title ;
         if   ( ! grade . equals ( "" ))
            result  +=   "  ["   +  grade  +   "]" ;
         return  result ;
     }
}

Chap16/POSGrades/POSGrades.java

Chap16/POSGrades/POSGrades.java

/**
 * Demonstrates the use of an Iterable object (and the technique for reading
 * a serialized object from a file).
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   POSGrades
{
     /**
     * Reads a serialized Program of Study, then prints all courses in which
     * a grade of A or A- was earned.
     */
     public   static   void  main ( String []  args )   throws   Exception
     {
         ProgramOfStudy  pos  =   ProgramOfStudy . load ( "ProgramOfStudy" );

         System . out . println ( pos );

         System . out . println ( "Classes with Grades of A or A-\n" );

         for   ( Course  course  :  pos )
         {
             if   ( course . getGrade (). equals ( "A" )   ||  course . getGrade (). equals ( "A-" ))
                 System . out . println ( course );
         }
     }
}

Chap16/POSGrades/ProgramOfStudy

Chap16/POSGrades/ProgramOfStudy.java

Chap16/POSGrades/ProgramOfStudy.java

import  java . io . FileInputStream ;
import  java . io . FileOutputStream ;
import  java . io . IOException ;
import  java . io . ObjectInputStream ;
import  java . io . ObjectOutputStream ;
import  java . io . Serializable ;
import  java . util . Iterator ;
import  java . util . LinkedList ;
import  java . util . List ;

/**
 * Represents a Program of Study, a list of courses taken and planned, for an
 * individual student.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ProgramOfStudy   implements   Iterable < Course > ,   Serializable
{
     private   List < Course >  list ;

     /**
     * Constructs an initially empty Program of Study.
     */
     public   ProgramOfStudy ()
     {
        list  =   new   LinkedList < Course > ();
     }

     /**
     * Adds the specified course to the end of the course list.
     * 
     *  @param  course the course to add
     */
     public   void  addCourse ( Course  course )
     {
         if   ( course  !=   null )
            list . add ( course );
     }

     /**
     * Finds and returns the course matching the specified prefix and number.
     * 
     *  @param  prefix the prefix of the target course
     *  @param  number the number of the target course
     *  @return  the course, or null if not found
     */
     public   Course  find ( String  prefix ,   int  number )
     {
         for   ( Course  course  :  list )
             if   ( prefix . equals ( course . getPrefix ())   &&
                    number  ==  course . getNumber ())
                 return  course ;

         return   null ;
     }

     /**
     * Adds the specified course after the target course. Does nothing if
     * either course is null or if the target is not found.
     * 
     *  @param  target the course after which the new course will be added
     *  @param  newCourse the course to add
     */
     public   void  addCourseAfter ( Course  target ,   Course  newCourse )
     {
         if   ( target  ==   null   ||  newCourse  ==   null )
             return ;

         int  targetIndex  =  list . indexOf ( target );
         if   ( targetIndex  !=   - 1 )
            list . add ( targetIndex  +   1 ,  newCourse );
     }

     /**
     * Replaces the specified target course with the new course. Does nothing if
     * either course is null or if the target is not found.
     * 
     *  @param  target the course to be replaced
     *  @param  newCourse the new course to add
     */
     public   void  replace ( Course  target ,   Course  newCourse )
     {
         if   ( target  ==   null   ||  newCourse  ==   null )
             return ;

         int  targetIndex  =  list . indexOf ( target );
         if   ( targetIndex  !=   - 1 )
            list . set ( targetIndex ,  newCourse );
     }

     /**
     * Creates and returns a string representation of this Program of Study.
     * 
     *  @return  a string representation of the Program of Study
     */
     public   String  toString ()
     {
         String  result  =   "" ;
         for   ( Course  course  :  list )
            result  +=  course  +   "\n" ;
         return  result ;
     }

     /**
     * Returns an iterator for this Program of Study.
     * 
     *  @return  an iterator for the Program of Study
     */
     public   Iterator < Course >  iterator ()
     {
         return  list . iterator ();
     }

     /**
     * Saves a serialized version of this Program of Study to the specified
     * file name.
     * 
     *  @param  fileName the file name under which the POS will be stored
     *  @throws  IOException
     */
     public   void  save ( String  fileName )   throws   IOException
     {
         FileOutputStream  fos  =   new   FileOutputStream ( fileName );  
         ObjectOutputStream  oos  =   new   ObjectOutputStream ( fos );  
        oos . writeObject ( this );  
        oos . flush ();  
        oos . close ();  
     }

     /**
     * Loads a serialized Program of Study from the specified file.
     * 
     *  @param  fileName the file from which the POS is read
     *  @return  the loaded Program of Study
     *  @throws  IOException
     *  @throws  ClassNotFoundException
     */
     public   static   ProgramOfStudy  load ( String  fileName )   throws   IOException ,   ClassNotFoundException
     {
         FileInputStream  fis  =   new   FileInputStream ( fileName );
         ObjectInputStream  ois  =   new   ObjectInputStream ( fis );
         ProgramOfStudy  pos  =   ( ProgramOfStudy )  ois . readObject ();
        ois . close ();

         return  pos ;
     }
}

Chap17/MazeTesterRecursive/Maze.java

Chap17/MazeTesterRecursive/Maze.java

import  java . util . * ;
import  java . io . * ;

/**
 * Maze represents a maze of characters. The goal is to get from the
 * top left corner to the bottom right, following a path of 1's. Arbitrary
 * constants are used to represent locations in the maze that have been TRIED
 * and that are part of the solution PATH.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   Maze
{
     private   static   final   int  TRIED  =   2 ;
     private   static   final   int  PATH  =   3 ;

     private   int  numberRows ,  numberColumns ;
     private   int [][]  grid ;

     /**
     * Constructor for the Maze class. Loads a maze from the given file.  
     * Throws a FileNotFoundException if the given file is not found.
     *
     *  @param  filename the name of the file to load
     *  @throws  FileNotFoundException if the given file is not found
     */
     public   Maze ( String  filename )   throws   FileNotFoundException
     {
         Scanner  scan  =   new   Scanner ( new   File ( filename ));
        numberRows  =  scan . nextInt ();
        numberColumns  =  scan . nextInt ();

        grid  =   new   int [ numberRows ][ numberColumns ];
         for   ( int  i  =   0 ;  i  <  numberRows ;  i ++ )
             for   ( int  j  =   0 ;  j  <  numberColumns ;  j ++ )
                grid [ i ][ j ]   =  scan . nextInt ();
     }

     /**
     * Marks the specified position in the maze as TRIED
     *
     *  @param  row the index of the row to try
     *  @param  col the index of the column to try 
     */
     public   void  tryPosition ( int  row ,   int  col )
     {
        grid [ row ][ col ]   =  TRIED ;
     }

     /**
     * Return the number of rows in this maze
     *
     *  @return  the number of rows in this maze
     */
     public   int  getRows ()
     {
         return  grid . length ;
     }

     /**
     * Return the number of columns in this maze
     *
     *  @return  the number of columns in this maze
     */
     public   int  getColumns ()
     {
         return  grid [ 0 ]. length ;
     }

     /**
     * Marks a given position in the maze as part of the PATH
     *
     *  @param  row the index of the row to mark as part of the PATH
     *  @param  col the index of the column to mark as part of the PATH 
     */
     public   void  markPath ( int  row ,   int  col )
     {
        grid [ row ][ col ]   =  PATH ;
     }

     /**
     * Determines if a specific location is valid. A valid location
     * is one that is on the grid, is not blocked, and has not been TRIED.
     *
     *  @param  row the row to be checked
     *  @param  column the column to be checked
     *  @return  true if the location is valid    
     */
     public   boolean  validPosition ( int  row ,   int  column )
     {
         boolean  result  =   false ;

         // check if cell is in the bounds of the matrix 
         if   ( row  >=   0   &&  row  <  grid . length  &&
                column  >=   0   &&  column  <  grid [ row ]. length )

             //  check if cell is not blocked and not previously tried 
             if   ( grid [ row ][ column ]   ==   1 )
                result  =   true ;

         return  result ;
     }

     /**
     * Returns the maze as a string.
     * 
     *  @return  a string representation of the maze
     */
     public   String  toString ()
     {
         String  result  =   "\n" ;

         for   ( int  row = 0 ;  row  <  grid . length ;  row ++ )
         {
             for   ( int  column = 0 ;  column  <  grid [ row ]. length ;  column ++ )
                result  +=  grid [ row ][ column ]   +   "" ;
            result  +=   "\n" ;
         }

         return  result ;
     }
}

Chap17/MazeTesterRecursive/MazeSolver.java

Chap17/MazeTesterRecursive/MazeSolver.java

/**
 * MazeSolver attempts to recursively traverse a Maze. The goal is to get from the
 * given starting position to the bottom right, following a path of 1's. Arbitrary
 * constants are used to represent locations in the maze that have been TRIED
 * and that are part of the solution PATH.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   MazeSolver
{
     private   Maze  maze ;

     /**
     * Constructor for the MazeSolver class.
     */
     public   MazeSolver ( Maze  maze )
     {
         this . maze  =  maze ;
     }

     /**
     * Attempts to recursively traverse the maze. Inserts special
     * characters indicating locations that have been TRIED and that
     * eventually become part of the solution PATH.
     *
     *  @param  row row index of current location
     *  @param  column column index of current location
     *  @return  true if the maze has been solved
     */
     public   boolean  traverse ( int  row ,   int  column )
     {
         boolean  done  =   false ;

         if   ( maze . validPosition ( row ,  column ))
         {
            maze . tryPosition ( row ,  column );     // mark this cell as tried

             if   ( row  ==  maze . getRows () - 1   &&  column  ==  maze . getColumns () - 1 )   
                done  =   true ;    // the maze is solved
             else
             {
                done  =  traverse ( row + 1 ,  column );        // down
                 if   ( ! done )
                    done  =  traverse ( row ,  column + 1 );    // right
                 if   ( ! done )
                    done  =  traverse ( row - 1 ,  column );    // up
                 if   ( ! done )
                    done  =  traverse ( row ,  column - 1 );    // left
             }

             if   ( done )    // this location is part of the final path
                maze . markPath ( row ,  column );
         }

         return  done ;
     }
}

Chap17/MazeTesterRecursive/MazeTester.java

Chap17/MazeTesterRecursive/MazeTester.java

import  java . util . * ;
import  java . io . * ;

/**
 * MazeTester uses recursion to determine if a maze can be traversed.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   MazeTester
{
     /**
     * Creates a new maze, prints its original form, attempts to
     * solve it, and prints out its final form.
     */
     public   static   void  main ( String []  args )   throws   FileNotFoundException
     {
         Scanner  scan  =   new   Scanner ( System . in );
         System . out . print ( "Enter the name of the file containing the maze: " );
         String  filename  =  scan . nextLine ();

         Maze  labyrinth  =   new   Maze ( filename );

         System . out . println ( labyrinth );

         MazeSolver  solver  =   new   MazeSolver ( labyrinth );

         if   ( solver . traverse ( 0 ,   0 ))
             System . out . println ( "The maze was successfully traversed!" );
         else
             System . out . println ( "There is no possible path." );

         System . out . println ( labyrinth );
     }
}

Chap17/MazeTesterRecursive/testfile.txt

5 5 1 0 0 0 0 1 1 1 1 0 0 1 0 0 0 1 1 1 1 0 0 1 0 1 1

Chap17/MazeTesterRecursive/testfile2.txt

21 35 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1

Chap17/MazeTesterRecursive/testfile3.txt

21 35 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 1 0 1 0 1 0 1 1 1 1 1 0 1 1 1 0 0 1 1 1 1 0 0 1 1 1 0 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 1 1 0 1

Chap17/TowersOfHanoi/SolveTowers.java

Chap17/TowersOfHanoi/SolveTowers.java

/**
 * SolveTowers uses recursion to solve the Towers of Hanoi puzzle.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   SolveTowers
{
     /**
     * Creates a TowersOfHanoi puzzle and solves it.
     */
     public   static   void  main ( String []  args )
     {
         TowersOfHanoi  towers  =   new   TowersOfHanoi ( 4 );
        towers . solve ();
     }
}

Chap17/TowersOfHanoi/TowersOfHanoi.java

Chap17/TowersOfHanoi/TowersOfHanoi.java

/**
 * TowersOfHanoi represents the classic Towers of Hanoi puzzle.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   TowersOfHanoi
{
     private   int  totalDisks ;

     /**
     * Sets up the puzzle with the specified number of disks.
     *
     *  @param  disks the number of disks 
     */
     public   TowersOfHanoi ( int  disks )
     {
        totalDisks  =  disks ;
     }

     /**
     * Performs the initial call to moveTower to solve the puzzle.
     * Moves the disks from tower 1 to tower 3 using tower 2.
     */
     public   void  solve ()
     {
        moveTower ( totalDisks ,   1 ,   3 ,   2 );
     }

     /**
     * Moves the specified number of disks from one tower to another
     * by moving a subtower of n-1 disks out of the way, moving one
     * disk, then moving the subtower back. Base case of 1 disk.
     *
     *  @param  numDisks  the number of disks to move
     *  @param  start     the starting tower
     *  @param  end       the ending tower
     *  @param  temp      the temporary tower
     */
     private   void  moveTower ( int  numDisks ,   int  start ,   int  end ,   int  temp )
     {
         if   ( numDisks  ==   1 )
            moveOneDisk ( start ,  end );
         else
         {
            moveTower ( numDisks - 1 ,  start ,  temp ,  end );
            moveOneDisk ( start ,  end );
            moveTower ( numDisks - 1 ,  temp ,  end ,  start );
         }
     }

     /**
     * Prints instructions to move one disk from the specified start
     * tower to the specified end tower.
     *
     *  @param  start  the starting tower
     *  @param  end    the ending tower
     */
     private   void  moveOneDisk ( int  start ,   int  end )
     {
         System . out . println ( "Move one disk from "   +  start  +   " to "   +  end );
     }
}

Chap18/ComparatorDemo/AssignmentComparator.java

Chap18/ComparatorDemo/AssignmentComparator.java

import  java . util . Comparator ;

/**
 * This Comparator sorts students by their assignment average.
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   AssignmentComparator   implements   Comparator < Student >
{
     /**
     * Compares two Student objects by their assignment average.
     */
    @ Override
     public   int  compare ( Student  o1 ,   Student  o2 )
     {
         Integer  average1  =  o1 . getAssignmentAverage ();
         Integer  average2  =  o2 . getAssignmentAverage ();

         return  average1 . compareTo ( average2 );
     }
}

Chap18/ComparatorDemo/ComparatorDemo.java

Chap18/ComparatorDemo/ComparatorDemo.java

import  java . util . Arrays ;

/**
 * Demonstrates sorting using a Comparator.
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ComparatorDemo
{
     /**
     * Creates several Student objects, then sorts them using three
     * different Comparator objects.
     *  @param  args command-line arguments (unused)
     */
     public   static   void  main ( String []  args )
     {
         Student []  students  =   new   Student [ 5 ];

        students [ 0 ]   =   new   Student ( "Mary" ,   97 ,   75 );
        students [ 1 ]   =   new   Student ( "James" ,   80 ,   80 );
        students [ 2 ]   =   new   Student ( "Mark" ,   75 ,   94 );
        students [ 3 ]   =   new   Student ( "Jolene" ,   95 ,   85 );
        students [ 4 ]   =   new   Student ( "Cassandra" ,   85 ,   75 );

         // output students before sort
         for   ( int  i  =   0 ;  i  <  students . length ;  i ++ )
             System . out . println ( students [ i ]);

         Arrays . sort ( students ,   new   ExamComparator ());

         // output students after sorting by exam average
         System . out . println ();
         System . out . println ( "After sorting by exam average:" );
         for   ( int  i  =   0 ;  i  <  students . length ;  i ++ )
             System . out . println ( students [ i ]);

         Arrays . sort ( students ,   new   AssignmentComparator ());

         // output students after sorting by assignment average
         System . out . println ();
         System . out . println ( "After sorting by assignment average:" );
         for   ( int  i  =   0 ;  i  <  students . length ;  i ++ )
             System . out . println ( students [ i ]);

         Arrays . sort ( students ,   new   OverallComparator ());

         // output students after sorting by overall average
         System . out . println ();
         System . out . println ( "After sorting by overall average:" );
         for   ( int  i  =   0 ;  i  <  students . length ;  i ++ )
             System . out . println ( students [ i ]);
     }
}

Chap18/ComparatorDemo/ExamComparator.java

Chap18/ComparatorDemo/ExamComparator.java

import  java . util . Comparator ;

/**
 * This Comparator sorts students by their exam average.
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ExamComparator   implements   Comparator < Student >
{
     /**
     * Compares two Student objects by their exam average.
     */
    @ Override
     public   int  compare ( Student  o1 ,   Student  o2 )
     {
         Integer  average1  =  o1 . getExamAverage ();
         Integer  average2  =  o2 . getExamAverage ();

         return  average1 . compareTo ( average2 );
     }
}

Chap18/ComparatorDemo/OverallComparator.java

Chap18/ComparatorDemo/OverallComparator.java

import  java . util . Comparator ;

/**
 * This Comparator sorts students by their overall average.
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   OverallComparator   implements   Comparator < Student >
{
     /**
     * Compares two Student objects by their overall average.
     */
    @ Override
     public   int  compare ( Student  o1 ,   Student  o2 )
     {
         Integer  average1  =  o1 . getOverallAverage ();
         Integer  average2  =  o2 . getOverallAverage ();

         return  average1 . compareTo ( average2 );
     }
}

Chap18/ComparatorDemo/Student.java

Chap18/ComparatorDemo/Student.java


/**
 * Represents a student in the Comparator example.
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   Student
{    
     private   String  id ;
     private   Integer  examAverage ;
     private   Integer  assignmentAverage ;
     private   Integer  overallAverage ;

     /**
     * Constructor for Student object.
     *  @param  id
     *  @param  examAverage
     *  @param  assignmentAverage
     */
     public   Student ( String  id ,   Integer  examAverage ,
             Integer  assignmentAverage )
     {
         this . id  =  id ;
         this . examAverage  =  examAverage ;
         this . assignmentAverage  =  assignmentAverage ;
         this . overallAverage  =   ( examAverage  +  assignmentAverage )   /   2 ;
     }

     /**
     * Getter for examAverage
     *  @return  examAverage 
     */
     public   Integer  getExamAverage ()
     {
         return  examAverage ;
     }

     /**
     * Getter for assignmentAverage
     *  @return  assignmentAverage 
     */
     public   Integer  getAssignmentAverage ()
     {
         return  assignmentAverage ;
     }

     /**
     * Getter for overallAverage
     *  @return  overallAverage 
     */
     public   Integer  getOverallAverage ()
     {
         return  overallAverage ;
     }

     /**
     * Provides a String representation of a Student object.
     *  @return  String representation of this Student object 
     */
     public   String  toString ()
     {
         return   ( id  +   " examAverage: "   +  examAverage  +
                 " assignmentAverage: "   +  assignmentAverage  +
                 " overallAverage: "   +  overallAverage  );
     }
}

Chap18/RadixSort/RadixSort.java

Chap18/RadixSort/RadixSort.java

import  java . util . * ;

/**
 * RadixSort driver demonstrates the use of queues in the execution of a radix sort.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   RadixSort      
{
     /**
     * Performs a radix sort on a set of numeric values.
     */
     public   static   void  main ( String []  args )
     {  
         int []  list  =   { 7843 ,   4568 ,   8765 ,   6543 ,   7865 ,   4532 ,   9987 ,   3241 ,
                 6589 ,   6622 ,   1211 };

         String  temp ;
         Integer  numObj ;
         int  digit ,  num ;

         Queue < Integer > []  digitQueues  =   ( LinkedList < Integer > [])( new   LinkedList [ 10 ]);
         for   ( int  digitVal  =   0 ;  digitVal  <=   9 ;  digitVal ++ )
            digitQueues [ digitVal ]   =   ( Queue < Integer > )( new   LinkedList < Integer > ());

         // sort the list
         for   ( int  position  =   0 ;  position  <=   3 ;  position ++ )
         {
             for   ( int  scan  =   0 ;  scan  <  list . length ;  scan ++ )
             {
                temp  =   String . valueOf ( list [ scan ]);
                digit  =   Character . digit ( temp . charAt ( 3 - position ),   10 );
                digitQueues [ digit ]. add ( new   Integer ( list [ scan ]));
             }

             // gather numbers back into list
            num  =   0 ;
             for   ( int  digitVal  =   0 ;  digitVal  <=   9 ;  digitVal ++ )
             {
                 while   ( ! ( digitQueues [ digitVal ]. isEmpty ()))
                 {
                    numObj  =  digitQueues [ digitVal ]. remove ();
                    list [ num ]   =  numObj . intValue ();
                    num ++ ;
                 }
             }
         }

         // output the sorted list
         for   ( int  scan  =   0 ;  scan  <  list . length ;  scan ++ )
             System . out . println ( list [ scan ]);
     }
}

Chap18/Searching/Searching.java

Chap18/Searching/Searching.java

/**
 * Searching demonstrates various search algorithms on an array 
 * of objects.
 *
 *  @author  Java Foundations
 *  @version  4.0 
 */
public   class   Searching  
{
     /**
     * Searches the specified array of objects using a linear search
     * algorithm.
     *
     *  @param  data   the array to be searched
     *  @param  min    the integer representation of the minimum value 
     *  @param  max    the integer representation of the maximum value
     *  @param  target the element being searched for
     *  @return        true if the desired element is found
     */
     public   static   < T >    
     boolean  linearSearch ( T []  data ,   int  min ,   int  max ,  T target )
     {
         int  index  =  min ;
         boolean  found  =   false ;

         while   ( ! found  &&  index  <=  max )  
         {
            found  =  data [ index ]. equals ( target );
            index ++ ;
         }

         return  found ;
     }

     /**
     * Searches the specified array of objects using a binary search
     * algorithm.
     *
     *  @param  data   the array to be searched
     *  @param  min    the integer representation of the minimum value 
     *  @param  max    the integer representation of the maximum value
     *  @param  target the element being searched for 
     *  @return        true if the desired element is found
     */
     public   static   < extends   Comparable < T >>   
     boolean  binarySearch ( T []  data ,   int  min ,   int  max ,  T target )
     {   
         boolean  found  =   false ;
         int  midpoint  =   ( min  +  max )   /   2 ;    // determine the midpoint

         if   ( data [ midpoint ]. compareTo ( target )   ==   0 )
            found  =   true ;
         else   if   ( data [ midpoint ]. compareTo ( target )   >   0 )
         {
             if   ( min  <=  midpoint  -   1 )
                found  =  binarySearch ( data ,  min ,  midpoint  -   1 ,  target );
         }
         else   if   ( midpoint  +   1   <=  max )
            found  =  binarySearch ( data ,  midpoint  +   1 ,  max ,  target );

         return  found ;
     }
}

Chap18/SortComparisonDemo/Driver.java

Chap18/SortComparisonDemo/Driver.java


/**
 * Driver of the Sort Comparison Demo
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   Driver
{
     /**
     * Presents the view for the Sort Comparison Demo.
     *  @param  args command-line arguments (unused)
     */
     public   static   void  main ( String []  args )
     {
         View  view  =   new   View ();
     }
}

Chap18/SortComparisonDemo/InsertionSortDemo.java

Chap18/SortComparisonDemo/InsertionSortDemo.java

import  javax . swing . * ;

/**
 * The InsertionSortDemo class serves as an example of using
 * Threads by extending the SwingWorker class.
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   InsertionSortDemo   extends   SwingWorker
{
     private   Integer []  data ;

     /**
     * Constructor for the InsertionSortDemo class
     *  @param  data the array of Integers to be sorted
     */
     public   InsertionSortDemo ( Integer []  data )
     {
         super ();
         this . data  =  data ;
     }

     /**
     * Overriding the SwingWorker doInBackGround method to 
     * call the insertionSort method
     *  @return  null - method requires a return
     */
    @ Override
     public   Void  doInBackground ()  
     {
        insertionSort ();
         return   null ;         
     }

     /**
     * Overriding the SwingWorker done method to wrap up
     * this thread. The get method is used to retrieve exceptions
     * that occur while the thread is running.
     */
    @ Override
     public   void  done ()
     {
         try  
         {
            setProgress ( 100 );
            get ();
         }
         catch   ( Exception  e )
         {
             System . out . println ( "An exception occurred while this "   +
                     "thread was running in the background" );
            e . printStackTrace ();
         }
     }

     /**
     * Sorts the specified array of objects using an insertion
     * sort algorithm.
     *
     *  @param  data the array to be sorted
     */
     private   void  insertionSort ()
     {
         for   ( int  index  =   1 ;  index  <  data . length ;  index ++ )
         {
             int  key  =  data [ index ];
             int  position  =  index ;
            updateProgress ( index );

             while   ( position  >   0   &&  data [ position - 1 ]. compareTo ( key )   >   0 )
             {
                data [ position ]   =  data [ position  -   1 ];
                position -- ;
             }

            data [ position ]   =  key ;
         }
     }

     /**
     * Calculates the current progress of the sort and updates the
     * progress attribute of the SwingWorker class. SwingWorker is
     * the parent of this class and provides the ability to add a
     * change listener.
     */  
     private   void  updateProgress ( int  numberOfPasses )
     {
         int  result ;
         double  progressCount  =   1   -   ((( double ) data . length  -
                 ( double ) numberOfPasses )   /   ( double ) data . length );
        result  =   ( int )   ( progressCount  *   100 );
        setProgress ( result );
     }
}

Chap18/SortComparisonDemo/QuickSortDemo.java

Chap18/SortComparisonDemo/QuickSortDemo.java

import  javax . swing . * ;

/**
 * The QuickSortDemo class serves as an example of using
 * Threads by extending the SwingWorker class.
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   QuickSortDemo   extends   SwingWorker
{
     private   Integer []  data ;
     private   int  numberOfPasses ;

     /**
     * Constructor for the QuickSortDemo class
     *  @param  data the array of Integers to be sorted
     */
     public   QuickSortDemo ( Integer []  data )
     {
         super ();
         this . data  =  data ;
     }

     /**
     * Overriding the SwingWorker doInBackGround method to 
     * call the quickSort method
     *  @return  null - method requires a return
     */
    @ Override
     public   Void  doInBackground ()  
     {
        quickSort ( data ,   0 ,  data . length  -   1 );
         return   null ;         
     }

     /**
     * Overriding the SwingWorker done method to wrap up
     * this thread. The get method is used to retrieve exceptions
     * that occur while the thread is running.
     */
    @ Override
     public   void  done ()
     {
         try  
         {
            setProgress ( 100 );
            get ();
         }
         catch   ( Exception  e )
         {
             System . out . println ( "An exception occurred while this "   +
                     "thread was running in the background" );
            e . printStackTrace ();
         }
     }

     /**
     * Recursively sorts a range of objects in the specified array using the
     * quick sort algorithm. 
     * 
     *  @param  data the array to be sorted
     *  @param  min  the minimum index in the range to be sorted
     *  @param  max  the maximum index in the range to be sorted
     */
     private   void  quickSort ( Integer []  data ,   int  min ,   int  max )
     {
         if   ( min  <  max )
         {
             int  indexofpartition  =  partition ( data ,  min ,  max );
            quickSort ( data ,  min ,  indexofpartition  -   1 );
            quickSort ( data ,  indexofpartition  +   1 ,  max );
         }
        numberOfPasses ++ ;
        updateProgress ();
     }

     /**
     * Used by the quick sort algorithm to find the partition.
     * 
     *  @param  data the array to be sorted
     *  @param  min  the minimum index in the range to be sorted
     *  @param  max  the maximum index in the range to be sorted
     */  
     private   int  partition ( Integer []  data ,   int  min ,   int  max )
     {
         Integer  partitionelement ;
         int  left ,  right ;
         int  middle  =   ( min  +  max )   /   2 ;

        partitionelement  =  data [ middle ];

        swap ( data ,  middle ,  min );

        left  =  min ;
        right  =  max ;

         try
         {
             while ( left  <  right )
             {
                 while   ( left  <  right  &&  data [ left ]. compareTo ( partitionelement )   <=   0 )
                    left ++ ;

                 while   ( data [ right ]. compareTo ( partitionelement )   >   0 )
                    right -- ;

                 if   ( left  <  right )
                    swap ( data ,  left ,  right );
             }
         }
         catch   ( Exception  e )   {  e . printStackTrace ();   }
        
        swap ( data ,  min ,  right );
         return  right ;
     }

     /**
     * Swaps to elements in an array. Used by various sorting algorithms.
     * 
     *  @param  data   the array in which the elements are swapped
     *  @param  index1 the index of the first element to be swapped
     *  @param  index2 the index of the second element to be swapped
     */  
     private   void  swap ( Integer []  data ,   int  index1 ,   int  index2 )
     {
         Integer  temp  =  data [ index1 ];
        data [ index1 ]   =  data [ index2 ];
        data [ index2 ]   =  temp ;
     }

     /**
     * Calculates the current progress of the sort and updates the
     * progress attribute of the SwingWorker class. SwingWorker is
     * the parent of this class and provides the ability to add a
     * change listener.
     *
     * Because of the possible unbalanced nature of a quicksort, it
     * is possible for the calculation to yield a result larger than
     * 100.  If that happens, the result is set to 100.
     */  
     private   void  updateProgress ()
     {
         int  result ;
         double  progressCount  =   1   -   ((( double ) data . length  -
                 ( double ) numberOfPasses )   /   ( double ) data . length );
        result  =   ( int )   ( progressCount  *   100 );
         if   ( result  >   100 )
            result  =   100 ;
        setProgress ( result );
     }
}

Chap18/SortComparisonDemo/View.java

Chap18/SortComparisonDemo/View.java

import  javax . swing . * ;
import  java . beans . * ;
import  java . awt . * ;
import  java . awt . event . ActionEvent ;
import  java . awt . event . ActionListener ;
import  java . util . Random ;

/**
 * Provides a graphical user interface for the thread sorts demo.
 *  @author  Java Foundations
 *  @version  4.0
 *
 */
public   class   View   implements   ActionListener ,   PropertyChangeListener
{
     private   JFrame  frame  =   new   JFrame ( "Thread Sorts Demo" );
     private   JPanel  pane  =   new   JPanel ( new   GridLayout ( 6 ,   1 ));

     private   JLabel  inputLabel  =   new   JLabel ( "Enter number between 1000 and 1000000" );
     private   JButton  go  =   new   JButton ( "Go" );
     private   JLabel  finished  =   new   JLabel ( "Process Status:" );

     private   JTextField  input  =   new   JTextField ();

     private   JPanel  inputPanel  =   new   JPanel ( new   FlowLayout ());

     private   JPanel  insertionPanel  =   new   JPanel ( new   FlowLayout ());

     private   JProgressBar  insertionBar  =   new   JProgressBar ();

     private   JPanel  quickPanel  =   new   JPanel ( new   FlowLayout ());

     private   JProgressBar  quickBar  =   new   JProgressBar ();

     private   int  userInput ;

     private   InsertionSortDemo  insertionSort ;
     private   QuickSortDemo  quickSort ;

     private   Integer []  data ;
     private   Integer []  insertionData ;
     private   Integer []  quickData ;

     private   JLabel  insertionLabel  =   new   JLabel ( "Insertion Sort:" );
     private   JLabel  quickLabel  =   new   JLabel ( "Quick Sort:" );

     /**
     * Constructor: Sets up and displays the GUI.
     */
     public   View ()
     {
        frame . setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
        frame . setLocationRelativeTo ( null );

        input . setPreferredSize ( new   Dimension ( 150 ,   25 ));
        inputPanel . add ( inputLabel );
        inputPanel . add ( input );
        inputPanel . add ( go );
        insertionPanel . add ( insertionLabel );
        insertionPanel . add ( insertionBar );
        quickPanel . add ( quickLabel );
        quickPanel . add ( quickBar );

        pane . add ( inputPanel );
        pane . add ( insertionPanel );
        pane . add ( quickPanel );
        pane . add ( finished );

        go . addActionListener ( this );

        frame . add ( pane );
        frame . pack ();
        frame . setVisible ( true );
        frame . setResizable ( false );
     }

     /**
     * Called when an object to which it is attached
     * receives an action event.
     *  @param  event the event to be handled
     */
    @ Override
     public   void  actionPerformed ( ActionEvent  event )  
     {
         if ( event . getSource ()   ==  go )
         {
             try
             {
                 if   ( Integer . parseInt ( input . getText ())   >   1000000   ||
                         Integer . parseInt ( input . getText ())   <   1000 )
                     JOptionPane . showMessageDialog ( null ,
                             "Enter an integer between 1000 and 1000000" );
                 else
                 {
                    userInput  =   Integer . parseInt ( input . getText ());
                    createArray ();
                    runThreads ();
                 }
             }
             catch   ( java . lang . NumberFormatException  e )
             {
                 JOptionPane . showMessageDialog ( null ,   "Input must be an integer between 1000 and 1000000" );
             }
         }
     }

     /**
     * Creates an array of randomly generated integers
     * and then copies it as needed.
     */
     private   void  createArray ()
     {
         //creates array 
        data  =   new   Integer [ userInput ];

         Random  generator  =   new   Random ();

         //loads array with random ints
         for ( int  x  =   0 ;  x  <  data . length ;  x ++ )
         {
            data [ x ]   =  generator . nextInt ( 1000000 );

         }
         //creates deep copies of array
        insertionData  =  data . clone ();
        quickData  =  data . clone ();
     }
    
     /**
     * Executes the SwingWorker threads.
     */
     private   void  runThreads ()
     {
         //passes these copies into runnable classes
        insertionSort  =   new   InsertionSortDemo ( insertionData );
        quickSort  =   new   QuickSortDemo ( quickData );

         //add change listeners for each of the demos
        insertionSort . addPropertyChangeListener ( this );
        quickSort . addPropertyChangeListener ( this );

         //starting threads
        insertionSort . execute ();
        quickSort . execute ();
     }

     /**
     * Called when an object to which it is attached
     * issues a property change event.
     *  @param  evt the event to be handeled
     */
     public   void  propertyChange ( PropertyChangeEvent  evt )  
     {
         if   ( evt . getSource (). equals ( insertionSort ))
         {
             if   ( "progress"   ==  evt . getPropertyName ())  
             {
                 int  progress  =   ( Integer )  evt . getNewValue ();
                 if   ( progress  ==   100 )  
                 {
                    insertionBar . setValue ( progress );
                    finished . setText ( "Process Status: complete" );
                 }
                 else  
                 {
                    finished . setText ( "Process Status: running" );
                    insertionBar . setValue ( progress );
                 }
             }
         }
         else   if   ( evt . getSource (). equals ( quickSort ))
         {
             if   ( "progress"   ==  evt . getPropertyName ())  
             {
                 int  progress  =   ( Integer )  evt . getNewValue ();
                 if   ( progress  ==   100 )  
                 {
                    quickBar . setValue ( progress );
                    finished . setText ( "Process Status: complete" );
                 }
                 else  
                 {
                    finished . setText ( "Process Status: running" );
                    quickBar . setValue ( progress );
                 }
             }
         }
     }
}

Chap18/Sorting/Contact.java

Chap18/Sorting/Contact.java

/**
 * Contact represents a phone contact.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   Contact   implements   Comparable < Contact >
{
     private   String  firstName ,  lastName ,  phone ;

     /**
     * Sets up this contact with the specified information.
     *
     *  @param  first     a string representation of a first name
     *  @param  last      a string representation of a last name
     *  @param  telephone a string representation of a phone number
     */
     public   Contact ( String  first ,   String  last ,   String  telephone )
     {
        firstName  =  first ;
        lastName  =  last ;
        phone  =  telephone ;
     }

     /**
     * Returns a description of this contact as a string.
     *
     *  @return  a string representation of this contact
     */
     public   String  toString ()
     {
         return  lastName  +   ", "   +  firstName  +   "\t"   +  phone ;
     }

     /**
     * Uses both last and first names to determine lexical ordering.
     *
     *  @param  other the contact to be compared to this contact
     *  @return       the integer result of the comparison
     */
     public   int  compareTo ( Contact  other )
     {
         int  result ;

         if   ( lastName . equals ( other . lastName ))
            result  =  firstName . compareTo ( other . firstName );
         else
            result  =  lastName . compareTo ( other . lastName );

         return  result ;
     }
}

Chap18/Sorting/Sorting.java

Chap18/Sorting/Sorting.java

/**
 * Sorting demonstrates sorting and searching on an array 
 * of objects.
 *
 *  @author  Java Foundations
 *  @version  4.0 
 */
public   class   Sorting  
{
     /**
     * Sorts the specified array of integers using the selection
     * sort algorithm.
     *
     *  @param  data the array to be sorted
     */
     public   static   < extends   Comparable < T >>  
     void  selectionSort ( T []  data )
     {
         int  min ;
        T temp ;

         for   ( int  index  =   0 ;  index  <  data . length  -   1 ;  index ++ )
         {
            min  =  index ;
             for   ( int  scan  =  index  +   1 ;  scan  <  data . length ;  scan ++ )
                 if   ( data [ scan ]. compareTo ( data [ min ])   <   0 )
                    min  =  scan ;

            swap ( data ,  min ,  index );
         }
     }

     /**
     * Swaps to elements in an array. Used by various sorting algorithms.
     * 
     *  @param  data   the array in which the elements are swapped
     *  @param  index1 the index of the first element to be swapped
     *  @param  index2 the index of the second element to be swapped
     */
     private   static   < extends   Comparable < T >>  
     void  swap ( T []  data ,   int  index1 ,   int  index2 )
     {
        T temp  =  data [ index1 ];
        data [ index1 ]   =  data [ index2 ];
        data [ index2 ]   =  temp ;
     }

     /**
     * Sorts the specified array of objects using an insertion
     * sort algorithm.
     *
     *  @param  data the array to be sorted
     */
     public   static   < extends   Comparable < T >>  
     void  insertionSort ( T []  data )
     {
         for   ( int  index  =   1 ;  index  <  data . length ;  index ++ )
         {
            T key  =  data [ index ];
             int  position  =  index ;

             // shift larger values to the right 
             while   ( position  >   0   &&  data [ position - 1 ]. compareTo ( key )   >   0 )
             {
                data [ position ]   =  data [ position  -   1 ];
                position -- ;
             }

            data [ position ]   =  key ;
         }
     }

     /**
     * Sorts the specified array of objects using a bubble sort
     * algorithm.
     *
     *  @param  data the array to be sorted
     */
     public   static   < extends   Comparable < T >>  
     void  bubbleSort ( T []  data )
     {
         int  position ,  scan ;

         for   ( position  =   data . length  -   1 ;  position  >=   0 ;  position -- )
         {
             for   ( scan  =   0 ;  scan  <=  position  -   1 ;  scan ++ )
             {
                 if   ( data [ scan ]. compareTo ( data [ scan  +   1 ])   >   0 )
                    swap ( data ,  scan ,  scan  +   1 );
             }
         }
     }

     /**
     * Sorts the specified array of objects using the quick sort algorithm.
     * 
     *  @param  data the array to be sorted
     */
     public   static   < extends   Comparable < T >>  
     void  quickSort ( T []  data )
     {
        quickSort ( data ,   0 ,  data . length  -   1 );
     }

     /**
     * Recursively sorts a range of objects in the specified array using the
     * quick sort algorithm. 
     * 
     *  @param  data the array to be sorted
     *  @param  min  the minimum index in the range to be sorted
     *  @param  max  the maximum index in the range to be sorted
     */
     private   static   < extends   Comparable < T >>  
     void  quickSort ( T []  data ,   int  min ,   int  max )
     {
         if   ( min  <  max )
         {
             // create partitions
             int  indexofpartition  =  partition ( data ,  min ,  max );

             // sort the left partition (lower values)
            quickSort ( data ,  min ,  indexofpartition  -   1 );

             // sort the right partition (higher values)
            quickSort ( data ,  indexofpartition  +   1 ,  max );
         }
     }

     /**
     * Used by the quick sort algorithm to find the partition.
     * 
     *  @param  data the array to be sorted
     *  @param  min  the minimum index in the range to be sorted
     *  @param  max  the maximum index in the range to be sorted
     */
     private   static   < extends   Comparable < T >>  
     int  partition ( T []  data ,   int  min ,   int  max )
     {
        T partitionelement ;
         int  left ,  right ;
         int  middle  =   ( min  +  max )   /   2 ;

         // use the middle data value as the partition element
        partitionelement  =  data [ middle ];
        
         // move it out of the way for now
        swap ( data ,  middle ,  min );

        left  =  min ;
        right  =  max ;

         while   ( left  <  right )
         {
             // search for an element that is > the partition element
             while   ( left  <  right  &&  data [ left ]. compareTo ( partitionelement )   <=   0 )
                left ++ ;

             // search for an element that is < the partition element
             while   ( data [ right ]. compareTo ( partitionelement )   >   0 )
                right -- ;

             // swap the elements
             if   ( left  <  right )
                swap ( data ,  left ,  right );
         }

         // move the partition element into place
        swap ( data ,  min ,  right );

         return  right ;
     }
    
     /**
     * Sorts the specified array of objects using the merge sort
     * algorithm.
     *
     *  @param  data the array to be sorted
     */
     public   static   < extends   Comparable < T >>
     void  mergeSort ( T []  data )
     {
        mergeSort ( data ,   0 ,  data . length  -   1 );
     }

     /**
     * Recursively sorts a range of objects in the specified array using the
     * merge sort algorithm.
     *
     *  @param  data the array to be sorted
     *  @param  min  the index of the first element 
     *  @param  max  the index of the last element
     */
     private   static   < extends   Comparable < T >>
     void  mergeSort ( T []  data ,   int  min ,   int  max )
     {
         if   ( min  <  max )
         {
             int  mid  =   ( min  +  max )   /   2 ;
            mergeSort ( data ,  min ,  mid );
            mergeSort ( data ,  mid + 1 ,  max );
            merge ( data ,  min ,  mid ,  max );
         }
     }

     /**
     * Merges two sorted subarrays of the specified array.
     *
     *  @param  data the array to be sorted
     *  @param  first the beginning index of the first subarray 
     *  @param  mid the ending index fo the first subarray
     *  @param  last the ending index of the second subarray
     */
    @ SuppressWarnings ( "unchecked" )
     private   static   < extends   Comparable < T >>
     void  merge ( T []  data ,   int  first ,   int  mid ,   int  last )
     {
        T []  temp  =   ( T [])( new   Comparable [ data . length ]);

         int  first1  =  first ,  last1  =  mid ;    // endpoints of first subarray
         int  first2  =  mid  +   1 ,  last2  =  last ;    // endpoints of second subarray
         int  index  =  first1 ;    // next index open in temp array

         //  Copy smaller item from each subarray into temp until one
         //  of the subarrays is exhausted
         while   ( first1  <=  last1  &&  first2  <=  last2 )
         {
             if   ( data [ first1 ]. compareTo ( data [ first2 ])   <   0 )
             {
                temp [ index ]   =  data [ first1 ];
                first1 ++ ;
             }
             else
             {
                temp [ index ]   =  data [ first2 ];
                first2 ++ ;
             }
            index ++ ;
         }

         //  Copy remaining elements from first subarray, if any
         while   ( first1  <=  last1 )
         {
            temp [ index ]   =  data [ first1 ];
            first1 ++ ;
            index ++ ;
         }

         //  Copy remaining elements from second subarray, if any
         while   ( first2  <=  last2 )
         {
            temp [ index ]   =  data [ first2 ];
            first2 ++ ;
            index ++ ;
         }

         //  Copy merged data into original array
         for   ( index  =  first ;  index  <=  last ;  index ++ )
            data [ index ]   =  temp [ index ];
     }

}

Chap18/Sorting/SortPhoneList.java

Chap18/Sorting/SortPhoneList.java

/**
 * SortPhoneList driver for testing an object selection sort.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   SortPhoneList
{
     /**
     * Creates an array of Contact objects, sorts them, then prints
     * them.
     */
     public   static   void  main ( String []  args )
     {
         Contact []  friends  =   new   Contact [ 7 ];

        friends [ 0 ]   =   new   Contact ( "John" ,   "Smith" ,   "610-555-7384" );
        friends [ 1 ]   =   new   Contact ( "Sarah" ,   "Barnes" ,   "215-555-3827" );
        friends [ 2 ]   =   new   Contact ( "Mark" ,   "Riley" ,   "733-555-2969" );
        friends [ 3 ]   =   new   Contact ( "Laura" ,   "Getz" ,   "663-555-3984" );
        friends [ 4 ]   =   new   Contact ( "Larry" ,   "Smith" ,   "464-555-3489" );
        friends [ 5 ]   =   new   Contact ( "Frank" ,   "Phelps" ,   "322-555-2284" );
        friends [ 6 ]   =   new   Contact ( "Marsha" ,   "Grant" ,   "243-555-2837" );

         Sorting . insertionSort ( friends );

         for   ( Contact  friend  :  friends )
             System . out . println ( friend );
     }
}

Chap19/BackPainAnalyzer/BackPainAnalyzer.java

Chap19/BackPainAnalyzer/BackPainAnalyzer.java

import  java . io . * ;

/**
 * BackPainAnaylyzer demonstrates the use of a binary decision tree to 
 * diagnose back pain.
 */
public   class   BackPainAnalyzer
{
     /**
     *  Asks questions of the user to diagnose a medical problem.
     */
     public   static   void  main ( String []  args )   throws   FileNotFoundException
     {
         System . out . println ( "So, you're having back pain." );

         DecisionTree  expert  =   new   DecisionTree ( "input.txt" );
        expert . evaluate ();
     }
}

Chap19/BackPainAnalyzer/DecisionTree.java

Chap19/BackPainAnalyzer/DecisionTree.java

import  jsjf . * ;
import  java . util . * ;
import  java . io . * ;

/**
 * The DecisionTree class uses the LinkedBinaryTree class to implement 
 * a binary decision tree. Tree elements are read from a given file and  
 * then the decision tree can be evaluated based on user input using the
 * evaluate method. 
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   DecisionTree
{
     private   LinkedBinaryTree < String >  tree ;

     /**
     * Builds the decision tree based on the contents of the given file
     *
     *  @param  filename the name of the input file
     *  @throws  FileNotFoundException if the input file is not found
     */
     public   DecisionTree ( String  filename )   throws   FileNotFoundException
     {
         File  inputFile  =   new   File ( filename );
         Scanner  scan  =   new   Scanner ( inputFile );
         int  numberNodes  =  scan . nextInt ();
        scan . nextLine ();
         int  root  =   0 ,  left ,  right ;

         List < LinkedBinaryTree < String >>  nodes  =   new  java . util . ArrayList < LinkedBinaryTree < String >> ();
        
         for   ( int  i  =   0 ;  i  <  numberNodes ;  i ++ )
            nodes . add ( i ,   new   LinkedBinaryTree < String > ( scan . nextLine ()));

         while   ( scan . hasNext ())
         {
            root  =  scan . nextInt ();
            left  =  scan . nextInt ();
            right  =  scan . nextInt ();
            scan . nextLine ();

            nodes . set ( root ,   new   LinkedBinaryTree < String > (( nodes . get ( root )). getRootElement (),  
                    nodes . get ( left ),  nodes . get ( right )));
         }
        
        tree  =  nodes . get ( root );
     }

     /**
     *  Follows the decision tree based on user responses.
     */
     public   void  evaluate ()
     {
         LinkedBinaryTree < String >  current  =  tree ;
         Scanner  scan  =   new   Scanner ( System . in );

         while   ( current . size ()   >   1 )
         {
             System . out . println ( current . getRootElement ());
             if   ( scan . nextLine (). equalsIgnoreCase ( "N" ))
                current  =  current . getLeft ();
             else
                current  =  current . getRight ();
         }

         System . out . println ( current . getRootElement ());
     }
}

Chap19/BackPainAnalyzer/input.txt

13 Did the pain occur after a blow or jolt? Do you have a fever? Do you have difficulty controlling your arms or legs? Do you have persistent morning stiffness? Do you have a sore throat or runny nose? Do you have pain or numbness in one arm or leg? Emergency! You may have damaged your spinal cord. See doctor if pain persists. You may have an inflammation of the joints. See doctor to address symptoms. You may have a respiratory infection. You may have a sprain or strain. You may have a muscle or nerve injury. 3 7 8 4 9 10 5 11 12 1 3 4 2 5 6 0 1 2

Chap19/BackPainAnalyzer/jsjf/ArrayList.java

Chap19/BackPainAnalyzer/jsjf/ArrayList.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . * ;

/**
 * ArrayList represents an array implementation of a list. The front of
 * the list is kept at array index 0. This class will be extended
 * to create a specific kind of list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   abstract   class   ArrayList < T >   implements   ListADT < T > ,   Iterable < T >
{
     private   final   static   int  DEFAULT_CAPACITY  =   100 ;
     private   final   static   int  NOT_FOUND  =   - 1 ;

     protected   int  rear ;
     protected  T []  list ;  
     protected   int  modCount ;

     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayList ()
     {
         this ( DEFAULT_CAPACITY );
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the integer value of the size of the array list
     */
     public   ArrayList ( int  initialCapacity )
     {
        rear  =   0 ;
        list  =   ( T [])( new   Object [ initialCapacity ]);
        modCount  =   0 ;
     }

     /**
     * Creates a new array to store the contents of this list with
     * twice the capacity of the old one. Called by descendant classes
     * that add elements to the list.
     */
     protected   void  expandCapacity ()
     {
         // To be completed as a Programming Project
     }

     /**
     * Removes and returns the last element in this list.
     *
     *  @return  the last element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeLast ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the first element in this list.
     *
     *  @return  the first element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeFirst ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the specified element.
     *
     *  @param   element the element to be removed and returned from the list
     *  @return  the removed elememt
     *  @throws  ElementNotFoundException if the element is not in the list
     */
     public  T remove ( T element )
     {
        T result ;
         int  index  =  find ( element );

         if   ( index  ==  NOT_FOUND )
             throw   new   ElementNotFoundException ( "ArrayList" );

        result  =  list [ index ];
        rear -- ;

         // shift the appropriate elements 
         for   ( int  scan  =  index ;  scan  <  rear ;  scan ++ )
            list [ scan ]   =  list [ scan + 1 ];

        list [ rear ]   =   null ;
        modCount ++ ;

         return  result ;
     }

     /**
     * Returns a reference to the element at the front of this list.
     * The element is not removed from the list.  Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the first element in the list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the element at the rear of this list.
     * The element is not removed from the list. Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the last element of this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T last ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this list contains the specified element.
     *
     *  @param  target the target element
     *  @return  true if the target is in the list, false otherwise 
     */
     public   boolean  contains ( T target )
     {
         return   ( find ( target )   !=  NOT_FOUND );
     }

     /**
     * Returns the array index of the specified element, or the
     * constant NOT_FOUND if it is not found.
     *
     *  @param  target the target element
     *  @return  the index of the target element, or the 
     *         NOT_FOUND constant
     */
     private   int  find ( T target )
     {
         int  scan  =   0 ;  
         int  result  =  NOT_FOUND ;

         if   ( ! isEmpty ())
             while   ( result  ==  NOT_FOUND  &&  scan  <  rear )
                 if   ( target . equals ( list [ scan ]))
                    result  =  scan ;
                 else
                    scan ++ ;

         return  result ;
     }

     /**
     * Returns true if this list is empty and false otherwise. 
     *
     *  @return  true if the list is empty, false otherwise
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements currently in this list.
     *
     *  @return  the number of elements in the list
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this list. 
     * 
     *  @return  the string representation of the list
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }

     /**
     * Returns an iterator for the elements currently in this list.
     * 
     *  @return  an iterator for the elements in the list
     */
     public   Iterator < T >  iterator ()
     {
         return   new   ArrayListIterator ();
     }

     /**
     * ArrayListIterator iterator over the elements of an ArrayList.
     */  
     private   class   ArrayListIterator   implements   Iterator < T >
     {
         int  iteratorModCount ;
         int  current ;

         /**
         * Sets up this iterator using the specified modCount.
         * 
         *  @param  modCount the current modification count for the ArrayList
         */
         public   ArrayListIterator ()
         {
            iteratorModCount  =  modCount ;
            current  =   0 ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( iteratorModCount  !=  modCount )
                 throw   new   ConcurrentModificationException ();

             return   ( current  <  rear );
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return   the next element in the iteration
         *  @throws   NoSuchElementException if an element not found exception occurs
         *  @throws   ConcurrentModificationException if the collection has changed
         */
         public  T next ()   throws   ConcurrentModificationException
         {
             if   ( ! hasNext ())
                 throw   new   NoSuchElementException ();

            current ++ ;

             return  list [ current  -   1 ];
         }

         /**
         * The remove operation is not supported in this collection.
         * 
         *  @throws  UnsupportedOperationException if the remove method is called
         */
         public   void  remove ()   throws   UnsupportedOperationException
         {
             throw   new   UnsupportedOperationException ();
         }

     }    
}

Chap19/BackPainAnalyzer/jsjf/ArrayUnorderedList.java

Chap19/BackPainAnalyzer/jsjf/ArrayUnorderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayUnorderedList represents an array implementation of an unordered list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayUnorderedList < T >   extends   ArrayList < T >  
implements   UnorderedListADT < T >
{
     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayUnorderedList ()
     {
         super ();
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the initial size of the list
     */
     public   ArrayUnorderedList ( int  initialCapacity )
     {
         super ( initialCapacity );
     }

     /**
     * Adds the specified element to the front of this list.
     * 
     *  @param  element the element to be added to the front of the list
     */
     public   void  addToFront ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element to the rear of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToRear ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element after the specified target element.
     * Throws an ElementNotFoundException if the target is not found.
     *
     *  @param  element the element to be added after the target element
     *  @param  target  the target that the element is to be added after
     */
     public   void  addAfter ( T element ,  T target )
     {
         if   ( size ()   ==  list . length )
            expandCapacity ();

         int  scan  =   0 ;

         // find the insertion point
         while   ( scan  <  rear  &&   ! target . equals ( list [ scan ]))  
            scan ++ ;

         if   ( scan  ==  rear )
             throw   new   ElementNotFoundException ( "UnorderedList" );

        scan ++ ;

         // shift elements up one
         for   ( int  shift  =  rear ;  shift  >  scan ;  shift -- )
            list [ shift ]   =  list [ shift  -   1 ];

         // insert element
        list [ scan ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }
}

Chap19/BackPainAnalyzer/jsjf/BinaryTreeADT.java

Chap19/BackPainAnalyzer/jsjf/BinaryTreeADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * BinaryTreeADT defines the interface to a binary tree data structure.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   BinaryTreeADT < T >  
{
     /** 
     * Returns a reference to the root element 
     *
     *  @return  a reference to the root
     */
     public  T getRootElement ();

     /** 
     * Returns true if this binary tree is empty and false otherwise.
     *
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ();

     /** 
     * Returns the number of elements in this binary tree.
     *
     *  @return  the number of elements in the tree
     */
     public   int  size ();

     /** 
     * Returns true if the binary tree contains an element that matches
     * the specified element and false otherwise. 
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the tree contains the target element
     */
     public   boolean  contains ( T targetElement );

     /** 
     * Returns a reference to the specified element if it is found in 
     * this binary tree. Throws an exception if the specified element
     * is not found.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  a reference to the specified element
     */
     public  T find ( T targetElement );

     /**  
     * Returns the string representation of this binary tree.
     *
     *  @return  a string representation of the binary tree
     */
     public   String  toString ();

     /**  
     * Returns an iterator over the elements of this tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns an iterator that represents an inorder traversal on this binary tree.  
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorInOrder ();

     /**  
     * Returns an iterator that represents a preorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPreOrder ();

     /**  
     * Returns an iterator that represents a postorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPostOrder ();

     /**  
     * Returns an iterator that represents a levelorder traversal on the binary tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ();
}

Chap19/BackPainAnalyzer/jsjf/BinaryTreeNode.java

Chap19/BackPainAnalyzer/jsjf/BinaryTreeNode.java

package  jsjf ;

/**
 * BinaryTreeNode represents a node in a binary tree with a left and 
 * right child.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   BinaryTreeNode < T >
{
     protected  T element ;
     protected   BinaryTreeNode < T >  left ,  right ;

     /**
     * Creates a new tree node with the specified data.
     *
     *  @param  obj the element that will become a part of the new tree node
     */
     public   BinaryTreeNode ( T obj )  
     {
        element  =  obj ;
        left  =   null ;
        right  =   null ;
     }

     /**
     * Creates a new tree node with the specified data.
     *
     *  @param  obj the element that will become a part of the new tree node
     *  @param  left the tree that will be the left subtree of this node
     *  @param  right the tree that will be the right subtree of this node
     */
     public   BinaryTreeNode ( T obj ,   LinkedBinaryTree < T >  left ,   LinkedBinaryTree < T >  right )  
     {
        element  =  obj ;
         if   ( left  ==   null )
             this . left  =   null ;
         else
             this . left  =  left . getRootNode ();

         if   ( right  ==   null )
             this . right  =   null ;
         else
             this . right  =  right . getRootNode ();
     }

     /**
     * Returns the number of non-null children of this node.
     *
     *  @return  the integer number of non-null children of this node 
     */
     public   int  numChildren ()  
     {
         int  children  =   0 ;

         if   ( left  !=   null )
            children  =   1   +  left . numChildren ();

         if   ( right  !=   null )
            children  =  children  +   1   +  right . numChildren ();

         return  children ;
     }

     /**
     * Return the element at this node.
     *
     *  @return  the element stored at this node
     */
     public  T getElement ()  
     {
         return  element ;
     }

     /**
     * Return the right child of this node.
     *
     *  @return  the right child of this node
     */
     public   BinaryTreeNode < T >  getRight ()  
     {
         return  right ;
     }

     /**
     * Sets the right child of this node.
     *
     *  @param  node the right child of this node
     */
     public   void  setRight ( BinaryTreeNode < T >  node )  
     {
        right  =  node ;
     }

     /**
     * Return the left child of this node.
     *
     *  @return  the left child of the node
     */
     public   BinaryTreeNode < T >  getLeft ()  
     {
         return  left ;
     }

     /**
     * Sets the left child of this node.
     *
     *  @param  node the left child of this node
     */
     public   void  setLeft ( BinaryTreeNode < T >  node )  
     {
        left  =  node ;
     }
}

Chap19/BackPainAnalyzer/jsjf/exceptions/ElementNotFoundException.java

Chap19/BackPainAnalyzer/jsjf/exceptions/ElementNotFoundException.java

package  jsjf . exceptions ;

/**
 * ElementNotFoundException represents the situation in which a target element 
 * is not present in a collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ElementNotFoundException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     */
     public   ElementNotFoundException   ( String  collection )
     {
         super   ( "The target element is not in this "   +  collection );
     }
}

Chap19/BackPainAnalyzer/jsjf/exceptions/EmptyCollectionException.java

Chap19/BackPainAnalyzer/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " is empty." );
     }
}

Chap19/BackPainAnalyzer/jsjf/exceptions/NonComparableElementException.java

Chap19/BackPainAnalyzer/jsjf/exceptions/NonComparableElementException.java

package  jsjf . exceptions ;

/**
 * NonComparableElementException  represents the situation in which an attempt 
 * is made to add an element that is not comparable to an ordered collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   NonComparableElementException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     * 
     *  @param  collection  the exception message to deliver
     */
     public   NonComparableElementException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " requires Comparable elements." );
     }
}

Chap19/BackPainAnalyzer/jsjf/LinkedBinaryTree.java

Chap19/BackPainAnalyzer/jsjf/LinkedBinaryTree.java

package  jsjf ;

import  java . util . * ;
import  jsjf . exceptions . * ;

/**
 * LinkedBinaryTree implements the BinaryTreeADT interface
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinkedBinaryTree < T >   implements   BinaryTreeADT < T > ,   Iterable < T >
{
     protected   BinaryTreeNode < T >  root ;  
     protected   int  modCount ;

     /**
     * Creates an empty binary tree.
     */
     public   LinkedBinaryTree ()  
     {
        root  =   null ;
     }

     /**
     * Creates a binary tree with the specified element as its root.
     *
     *  @param  element the element that will become the root of the binary tree
     */
     public   LinkedBinaryTree ( T element )  
     {
        root  =   new   BinaryTreeNode < T > ( element );
     }

     /**
     * Creates a binary tree with the specified element as its root and the 
     * given trees as its left child and right child
     *
     *  @param  element the element that will become the root of the binary tree
     *  @param  left the left subtree of this tree
     *  @param  right the right subtree of this tree
     */
     public   LinkedBinaryTree ( T element ,   LinkedBinaryTree < T >  left ,  
             LinkedBinaryTree < T >  right )  
     {
        root  =   new   BinaryTreeNode < T > ( element );
        root . setLeft ( left . root );
        root . setRight ( right . root );
     }

     /**
     * Returns a reference to the element at the root
     *
     *  @return  a reference to the specified target
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T getRootElement ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the node at the root
     *
     *  @return  a reference to the specified node
     *  @throws  EmptyCollectionException if the tree is empty
     */
     protected   BinaryTreeNode < T >  getRootNode ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the left subtree of the root of this tree.
     *
     *  @return  a link to the left subtree fo the tree
     */
     public   LinkedBinaryTree < T >  getLeft ()
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the right subtree of the root of this tree.
     *
     *  @return  a link to the right subtree of the tree
     */
     public   LinkedBinaryTree < T >  getRight ()
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this binary tree is empty and false otherwise.
     *
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ()  
     {
         return   ( root  ==   null );
     }

     /**
     * Returns the integer size of this tree.
     *
     *  @return  the integer size of the tree
     */
     public   int  size ()  
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns the height of this tree.
     *
     *  @return  the height of the tree
     */
     public   int  getHeight ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns the height of the specified node.
     *
     *  @param  node the node from which to calculate the height
     *  @return  the height of the tree
     */
     private   int  height ( BinaryTreeNode < T >  node )  
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns true if this tree contains an element that matches the
     * specified target element and false otherwise.
     *
     *  @param  targetElement the element being sought in this tree
     *  @return  true if the element in is this tree, false otherwise
     */
     public   boolean  contains ( T targetElement )  
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this binary tree.  Throws a ElementNotFoundException if
     * the specified target element is not found in the binary tree.
     *
     *  @param  targetElement the element being sought in this tree
     *  @return  a reference to the specified target
     *  @throws  ElementNotFoundException if the element is not in the tree
     */
     public  T find ( T targetElement )   throws   ElementNotFoundException
     {
         BinaryTreeNode < T >  current  =  findNode ( targetElement ,  root );

         if   ( current  ==   null )
             throw   new   ElementNotFoundException ( "LinkedBinaryTree" );

         return   ( current . getElement ());
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this binary tree.
     *
     *  @param  targetElement the element being sought in this tree
     *  @param  next the element to begin searching from
     */
     private   BinaryTreeNode < T >  findNode ( T targetElement ,  
             BinaryTreeNode < T >  next )
     {
         if   ( next  ==   null )
             return   null ;

         if   ( next . getElement (). equals ( targetElement ))
             return  next ;

         BinaryTreeNode < T >  temp  =  findNode ( targetElement ,  next . getLeft ());

         if   ( temp  ==   null )
            temp  =  findNode ( targetElement ,  next . getRight ());

         return  temp ;
     }

     /**
     * Returns a string representation of this binary tree showing
     * the nodes in an inorder fashion.
     *
     *  @return  a string representation of this binary tree
     */
     public   String  toString ()  
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }

     /**
     * Returns an iterator over the elements in this tree using the 
     * iteratorInOrder method
     *
     *  @return  an in order iterator over this binary tree
     */
     public   Iterator < T >  iterator ()
     {
         return  iteratorInOrder ();
     }

     /**
     * Performs an inorder traversal on this binary tree by calling an
     * overloaded, recursive inorder method that starts with
     * the root.
     *
     *  @return  an in order iterator over this binary tree
     */
     public   Iterator < T >  iteratorInOrder ()
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        inOrder ( root ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive inorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  inOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  !=   null )
         {
            inOrder ( node . getLeft (),  tempList );
            tempList . addToRear ( node . getElement ());
            inOrder ( node . getRight (),  tempList );
         }
     }

     /**
     * Performs an preorder traversal on this binary tree by calling 
     * an overloaded, recursive preorder method that starts with
     * the root.
     *
     *  @return  a pre order iterator over this tree
     */
     public   Iterator < T >  iteratorPreOrder ()  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Performs a recursive preorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  preOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         // To be completed as a Programming Project
     }

     /**
     * Performs an postorder traversal on this binary tree by calling
     * an overloaded, recursive postorder method that starts
     * with the root.
     *
     *  @return  a post order iterator over this tree
     */
     public   Iterator < T >  iteratorPostOrder ()  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Performs a recursive postorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  postOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         // To be completed as a Programming Project
     }

     /**
     * Performs a levelorder traversal on this binary tree, using a
     * templist.
     *
     *  @return  a levelorder iterator over this binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ()  
     {
         ArrayUnorderedList < BinaryTreeNode < T >>  nodes  =  
                 new   ArrayUnorderedList < BinaryTreeNode < T >> ();
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
         BinaryTreeNode < T >  current ;

        nodes . addToRear ( root );

         while   ( ! nodes . isEmpty ())  
         {
            current  =  nodes . removeFirst ();

             if   ( current  !=   null )
             {
                tempList . addToRear ( current . getElement ());
                 if   ( current . getLeft ()   !=   null )
                    nodes . addToRear ( current . getLeft ());
                 if   ( current . getRight ()   !=   null )
                    nodes . addToRear ( current . getRight ());
             }
             else
                tempList . addToRear ( null );
         }

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Inner class to represent an iterator over the elements of this tree
     */
     private   class   TreeIterator   implements   Iterator < T >
     {
         private   int  expectedModCount ;
         private   Iterator < T >  iter ;

         /**
         * Sets up this iterator using the specified iterator.
         *
         *  @param  iter the list iterator created by a tree traversal
         */
         public   TreeIterator ( Iterator < T >  iter )
         {
             this . iter  =  iter ;
            expectedModCount  =  modCount ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( ! ( modCount  ==  expectedModCount ))
                 throw   new   ConcurrentModificationException ();

             return   ( iter . hasNext ());
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return  the next element in the iteration
         *  @throws  NoSuchElementException if the iterator is empty
         */
         public  T next ()   throws   NoSuchElementException
         {
             if   ( hasNext ())
                 return   ( iter . next ());
             else  
                 throw   new   NoSuchElementException ();
         }

         /**
         * The remove operation is not supported.
         * 
         *  @throws  UnsupportedOperationException if the remove operation is called
         */
         public   void  remove ()
         {
             throw   new   UnsupportedOperationException ();
         }
     }
}

Chap19/BackPainAnalyzer/jsjf/ListADT.java

Chap19/BackPainAnalyzer/jsjf/ListADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * ListADT defines the interface to a general list collection. Specific
 * types of lists will extend this interface to complete the
 * set of necessary operations.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   ListADT < T >   extends   Iterable < T >
{
     /**  
     * Removes and returns the first element from this list. 
     * 
     *  @return  the first element from this list
     */
     public  T removeFirst ();

     /**  
     * Removes and returns the last element from this list. 
     *
     *  @return  the last element from this list
     */
     public  T removeLast ();

     /**  
     * Removes and returns the specified element from this list. 
     *
     *  @param  element the element to be removed from the list
     */
     public  T remove ( T element );

     /**  
     * Returns a reference to the first element in this list. 
     *
     *  @return  a reference to the first element in this list
     */
     public  T first ();

     /**  
     * Returns a reference to the last element in this list. 
     *
     *  @return  a reference to the last element in this list
     */
     public  T last ();

     /**  
     * Returns true if this list contains the specified target element. 
     *
     *  @param  target the target that is being sought in the list
     *  @return  true if the list contains this element
     */
     public   boolean  contains ( T target );

     /**  
     * Returns true if this list contains no elements. 
     *
     *  @return  true if this list contains no elements
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this list. 
     *
     *  @return  the integer representation of number of elements in this list
     */
     public   int  size ();

     /**  
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements in this list
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns a string representation of this list. 
     *
     *  @return  a string representation of this list
     */
     public   String  toString ();
}

Chap19/BackPainAnalyzer/jsjf/UnorderedListADT.java

Chap19/BackPainAnalyzer/jsjf/UnorderedListADT.java

package  jsjf ;

/**
 * UnorderedListADT defines the interface to an unordered list collection. 
 * Elements are stored in any order the user desires.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   UnorderedListADT < T >   extends   ListADT < T >
{
     /**  
     * Adds the specified element to the front of this list. 
     *
     *  @param  element the element to be added to the front of this list    
     */
     public   void  addToFront ( T element );   

     /**  
     * Adds the specified element to the rear of this list. 
     *
     *  @param  element the element to be added to the rear of this list    
     */
     public   void  addToRear ( T element );  

     /**  
     * Adds the specified element after the specified target. 
     *
     *  @param  element the element to be added after the target
     *  @param  target  the target is the item that the element will be added
     *                after    
     */
     public   void  addAfter ( T element ,  T target );
}

Chap19/ExpressionTrees/ExpressionTree.java

Chap19/ExpressionTrees/ExpressionTree.java

import  jsjf . * ;

/**
 * ExpressionTree represents an expression tree of operators and operands.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ExpressionTree   extends   LinkedBinaryTree < ExpressionTreeOp >
{
     /**
     * Creates an empty expression tree.
     */
     public   ExpressionTree ()  
     {
         super ();
     }

     /**
     * Constructs a expression tree from the two specified expression 
     * trees.
     *
     *  @param  element      the expression tree for the center
     *  @param  leftSubtree  the expression tree for the left subtree
     *  @param  rightSubtree the expression tree for the right subtree
     */
     public   ExpressionTree ( ExpressionTreeOp  element ,
             ExpressionTree  leftSubtree ,   ExpressionTree  rightSubtree )  
     {
        root  =   new   BinaryTreeNode < ExpressionTreeOp > ( element ,  leftSubtree ,
                rightSubtree );
     }

     /**
     * Evaluates the expression tree by calling the recursive 
     * evaluateNode method.
     *
     *  @return  the integer evaluation of the tree
     */
     public   int  evaluateTree ()  
     {
         return  evaluateNode ( root );
     }

     /**
     * Recursively evaluates each node of the tree.
     *
     *  @param  root the root of the tree to be evaluated
     *  @return  the integer evaluation of the tree
     */
     public   int  evaluateNode ( BinaryTreeNode  root )  
     {
         int  result ,  operand1 ,  operand2 ;
         ExpressionTreeOp  temp ;

         if   ( root == null )
            result  =   0 ;
         else
         {
            temp  =   ( ExpressionTreeOp ) root . getElement ();

             if   ( temp . isOperator ())
             {
                operand1  =  evaluateNode ( root . getLeft ());
                operand2  =  evaluateNode ( root . getRight ());
                result  =  computeTerm ( temp . getOperator (),  operand1 ,  operand2 );
             }
             else
                result  =  temp . getValue ();
         }

         return  result ;
     }

     /**
     * Evaluates a term consisting of an operator and two operands.
     *
     *  @param  operator  the operator for the expression
     *  @param  operand1  the first operand for the expression
     *  @param  operand2  the second operand for the expression
     */
     private   static   int  computeTerm ( char  operator ,   int  operand1 ,   int  operand2 )
     {
         int  result = 0 ;

         if   ( operator  ==   '+' )
            result  =  operand1  +  operand2 ;
         else   if   ( operator  ==   '-' )
            result  =  operand1  -  operand2 ;
         else   if   ( operator  ==   '*' )
            result  =  operand1  *  operand2 ;
         else  
            result  =  operand1  /  operand2 ;

         return  result ;
     }

     /**
     * Generates a structured string version of the tree by performing 
     * a levelorder traversal.
     *
     *  @return  a string representation of this binary tree
     */
     public   String  printTree ()  
     {
         UnorderedListADT < BinaryTreeNode < ExpressionTreeOp >>  nodes  =  
                 new   ArrayUnorderedList < BinaryTreeNode < ExpressionTreeOp >> ();
         UnorderedListADT < Integer >  levelList  =  
                 new   ArrayUnorderedList < Integer > ();
         BinaryTreeNode < ExpressionTreeOp >  current ;
         String  result  =   "" ;
         int  printDepth  =   this . getHeight ();
         int  possibleNodes  =   ( int )   Math . pow ( 2 ,  printDepth  +   1 );
         int  countNodes  =   0 ;

        nodes . addToRear ( root );
         Integer  currentLevel  =   0 ;
         Integer  previousLevel  =   - 1 ;
        levelList . addToRear ( currentLevel );

         while   ( countNodes  <  possibleNodes )  
         {
            countNodes  =  countNodes  +   1 ;
            current  =  nodes . removeFirst ();
            currentLevel  =  levelList . removeFirst ();
             if   ( currentLevel  >  previousLevel )
             {
                result  =  result  +   "\n\n" ;
                previousLevel  =  currentLevel ;
                 for   ( int  j  =   0 ;  j  <   (( Math . pow ( 2 ,   ( printDepth  -  currentLevel )))   -   1 );  j ++ )
                    result  =  result  +   " " ;
             }
             else
             {
                 for   ( int  i  =   0 ;  i  <   (( Math . pow ( 2 ,   ( printDepth  -  currentLevel  +   1 ))   -   1 ))   ;  i ++ )  
                 {
                    result  =  result  +   " " ;
                 }
             }
             if   ( current  !=   null )
             {
                result  =  result  +   ( current . getElement ()). toString ();
                nodes . addToRear ( current . getLeft ());
                levelList . addToRear ( currentLevel  +   1 );
                nodes . addToRear ( current . getRight ());
                levelList . addToRear ( currentLevel  +   1 );
             }
             else  
             {
                nodes . addToRear ( null );
                levelList . addToRear ( currentLevel  +   1 );
                nodes . addToRear ( null );
                levelList . addToRear ( currentLevel  +   1 );
                result  =  result  +   " " ;
             }

         }

         return  result ;
     }
}

Chap19/ExpressionTrees/ExpressionTreeOp.java

Chap19/ExpressionTrees/ExpressionTreeOp.java

import  jsjf . * ;

/**
 * ExpressionTreeOp represents an element in an expression tree.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ExpressionTreeOp  
{
     private   int  termType ;
     private   char  operator ;
     private   int  value ;

     /**
     * Creates a new expression tree object with the specified data.
     *
     *  @param  type the integer type of the expression
     *  @param  op   the operand for the expression
     *  @param  val  the value for the expression
     */
     public   ExpressionTreeOp ( int  type ,   char  op ,   int  val )  
     {
        termType  =  type ;
        operator  =  op ;
        value  =  val ;
     }

     /**
     * Returns true if this object is an operator and false otherwise.
     *
     *  @return  true if this object is an operator, false otherwise
     */
     public   boolean  isOperator ()  
     {
         return   ( termType  ==   1 );
     }

     /**
     *Returns the operator of this expression tree object.
     *
     *  @return  the character representation of the operator
     */
     public   char  getOperator ()  
     {
         return  operator ;
     }

     /**
     * Returns the value of this expression tree object.
     *
     *  @return  the value of this expression tree object
     */
     public   int  getValue ()  
     {
         return  value ;
     }

     public   String  toString ()
     {
         if   ( termType  ==   1 )  
             return  operator  +   "" ;
         else
             return  value  +   "" ;
     }
}


Chap19/ExpressionTrees/jsjf/ArrayList.java

Chap19/ExpressionTrees/jsjf/ArrayList.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . * ;

/**
 * ArrayList represents an array implementation of a list. The front of
 * the list is kept at array index 0. This class will be extended
 * to create a specific kind of list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   abstract   class   ArrayList < T >   implements   ListADT < T > ,   Iterable < T >
{
     private   final   static   int  DEFAULT_CAPACITY  =   100 ;
     private   final   static   int  NOT_FOUND  =   - 1 ;

     protected   int  rear ;
     protected  T []  list ;  
     protected   int  modCount ;

     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayList ()
     {
         this ( DEFAULT_CAPACITY );
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the integer value of the size of the array list
     */
     public   ArrayList ( int  initialCapacity )
     {
        rear  =   0 ;
        list  =   ( T [])( new   Object [ initialCapacity ]);
        modCount  =   0 ;
     }

     /**
     * Creates a new array to store the contents of this list with
     * twice the capacity of the old one. Called by descendant classes
     * that add elements to the list.
     */
     protected   void  expandCapacity ()
     {
         // To be completed as a Programming Project
     }

     /**
     * Removes and returns the last element in this list.
     *
     *  @return  the last element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeLast ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the first element in this list.
     *
     *  @return  the first element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeFirst ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the specified element.
     *
     *  @param   element the element to be removed and returned from the list
     *  @return  the removed elememt
     *  @throws  ElementNotFoundException if the element is not in the list
     */
     public  T remove ( T element )
     {
        T result ;
         int  index  =  find ( element );

         if   ( index  ==  NOT_FOUND )
             throw   new   ElementNotFoundException ( "ArrayList" );

        result  =  list [ index ];
        rear -- ;

         // shift the appropriate elements 
         for   ( int  scan  =  index ;  scan  <  rear ;  scan ++ )
            list [ scan ]   =  list [ scan + 1 ];

        list [ rear ]   =   null ;
        modCount ++ ;

         return  result ;
     }

     /**
     * Returns a reference to the element at the front of this list.
     * The element is not removed from the list.  Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the first element in the list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the element at the rear of this list.
     * The element is not removed from the list. Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the last element of this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T last ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this list contains the specified element.
     *
     *  @param  target the target element
     *  @return  true if the target is in the list, false otherwise 
     */
     public   boolean  contains ( T target )
     {
         return   ( find ( target )   !=  NOT_FOUND );
     }

     /**
     * Returns the array index of the specified element, or the
     * constant NOT_FOUND if it is not found.
     *
     *  @param  target the target element
     *  @return  the index of the target element, or the 
     *         NOT_FOUND constant
     */
     private   int  find ( T target )
     {
         int  scan  =   0 ;  
         int  result  =  NOT_FOUND ;

         if   ( ! isEmpty ())
             while   ( result  ==  NOT_FOUND  &&  scan  <  rear )
                 if   ( target . equals ( list [ scan ]))
                    result  =  scan ;
                 else
                    scan ++ ;

         return  result ;
     }

     /**
     * Returns true if this list is empty and false otherwise. 
     *
     *  @return  true if the list is empty, false otherwise
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements currently in this list.
     *
     *  @return  the number of elements in the list
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this list. 
     * 
     *  @return  the string representation of the list
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }

     /**
     * Returns an iterator for the elements currently in this list.
     * 
     *  @return  an iterator for the elements in the list
     */
     public   Iterator < T >  iterator ()
     {
         return   new   ArrayListIterator ();
     }

     /**
     * ArrayListIterator iterator over the elements of an ArrayList.
     */  
     private   class   ArrayListIterator   implements   Iterator < T >
     {
         int  iteratorModCount ;
         int  current ;

         /**
         * Sets up this iterator using the specified modCount.
         * 
         *  @param  modCount the current modification count for the ArrayList
         */
         public   ArrayListIterator ()
         {
            iteratorModCount  =  modCount ;
            current  =   0 ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( iteratorModCount  !=  modCount )
                 throw   new   ConcurrentModificationException ();

             return   ( current  <  rear );
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return   the next element in the iteration
         *  @throws   NoSuchElementException if an element not found exception occurs
         *  @throws   ConcurrentModificationException if the collection has changed
         */
         public  T next ()   throws   ConcurrentModificationException
         {
             if   ( ! hasNext ())
                 throw   new   NoSuchElementException ();

            current ++ ;

             return  list [ current  -   1 ];
         }

         /**
         * The remove operation is not supported in this collection.
         * 
         *  @throws  UnsupportedOperationException if the remove method is called
         */
         public   void  remove ()   throws   UnsupportedOperationException
         {
             throw   new   UnsupportedOperationException ();
         }

     }    
}

Chap19/ExpressionTrees/jsjf/ArrayUnorderedList.java

Chap19/ExpressionTrees/jsjf/ArrayUnorderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayUnorderedList represents an array implementation of an unordered list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayUnorderedList < T >   extends   ArrayList < T >  
implements   UnorderedListADT < T >
{
     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayUnorderedList ()
     {
         super ();
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the initial size of the list
     */
     public   ArrayUnorderedList ( int  initialCapacity )
     {
         super ( initialCapacity );
     }

     /**
     * Adds the specified element to the front of this list.
     * 
     *  @param  element the element to be added to the front of the list
     */
     public   void  addToFront ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element to the rear of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToRear ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element after the specified target element.
     * Throws an ElementNotFoundException if the target is not found.
     *
     *  @param  element the element to be added after the target element
     *  @param  target  the target that the element is to be added after
     */
     public   void  addAfter ( T element ,  T target )
     {
         if   ( size ()   ==  list . length )
            expandCapacity ();

         int  scan  =   0 ;

         // find the insertion point
         while   ( scan  <  rear  &&   ! target . equals ( list [ scan ]))  
            scan ++ ;

         if   ( scan  ==  rear )
             throw   new   ElementNotFoundException ( "UnorderedList" );

        scan ++ ;

         // shift elements up one
         for   ( int  shift  =  rear ;  shift  >  scan ;  shift -- )
            list [ shift ]   =  list [ shift  -   1 ];

         // insert element
        list [ scan ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }
}

Chap19/ExpressionTrees/jsjf/BinaryTreeADT.java

Chap19/ExpressionTrees/jsjf/BinaryTreeADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * BinaryTreeADT defines the interface to a binary tree data structure.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   BinaryTreeADT < T >  
{
     /** 
     * Returns a reference to the root element 
     *
     *  @return  a reference to the root
     */
     public  T getRootElement ();

     /** 
     * Returns true if this binary tree is empty and false otherwise.
     *
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ();

     /** 
     * Returns the number of elements in this binary tree.
     *
     *  @return  the number of elements in the tree
     */
     public   int  size ();

     /** 
     * Returns true if the binary tree contains an element that matches
     * the specified element and false otherwise. 
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the tree contains the target element
     */
     public   boolean  contains ( T targetElement );

     /** 
     * Returns a reference to the specified element if it is found in 
     * this binary tree. Throws an exception if the specified element
     * is not found.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  a reference to the specified element
     */
     public  T find ( T targetElement );

     /**  
     * Returns the string representation of this binary tree.
     *
     *  @return  a string representation of the binary tree
     */
     public   String  toString ();

     /**  
     * Returns an iterator over the elements of this tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns an iterator that represents an inorder traversal on this binary tree.  
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorInOrder ();

     /**  
     * Returns an iterator that represents a preorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPreOrder ();

     /**  
     * Returns an iterator that represents a postorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPostOrder ();

     /**  
     * Returns an iterator that represents a levelorder traversal on the binary tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ();
}

Chap19/ExpressionTrees/jsjf/BinaryTreeNode.java

Chap19/ExpressionTrees/jsjf/BinaryTreeNode.java

package  jsjf ;

/**
 * BinaryTreeNode represents a node in a binary tree with a left and 
 * right child.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   BinaryTreeNode < T >
{
     protected  T element ;
     protected   BinaryTreeNode < T >  left ,  right ;

     /**
     * Creates a new tree node with the specified data.
     *
     *  @param  obj the element that will become a part of the new tree node
     */
     public   BinaryTreeNode ( T obj )  
     {
        element  =  obj ;
        left  =   null ;
        right  =   null ;
     }

     /**
     * Creates a new tree node with the specified data.
     *
     *  @param  obj the element that will become a part of the new tree node
     *  @param  left the tree that will be the left subtree of this node
     *  @param  right the tree that will be the right subtree of this node
     */
     public   BinaryTreeNode ( T obj ,   LinkedBinaryTree < T >  left ,   LinkedBinaryTree < T >  right )  
     {
        element  =  obj ;
         if   ( left  ==   null )
             this . left  =   null ;
         else
             this . left  =  left . getRootNode ();

         if   ( right  ==   null )
             this . right  =   null ;
         else
             this . right  =  right . getRootNode ();
     }

     /**
     * Returns the number of non-null children of this node.
     *
     *  @return  the integer number of non-null children of this node 
     */
     public   int  numChildren ()  
     {
         int  children  =   0 ;

         if   ( left  !=   null )
            children  =   1   +  left . numChildren ();

         if   ( right  !=   null )
            children  =  children  +   1   +  right . numChildren ();

         return  children ;
     }

     /**
     * Return the element at this node.
     *
     *  @return  the element stored at this node
     */
     public  T getElement ()  
     {
         return  element ;
     }

     /**
     * Return the right child of this node.
     *
     *  @return  the right child of this node
     */
     public   BinaryTreeNode < T >  getRight ()  
     {
         return  right ;
     }

     /**
     * Sets the right child of this node.
     *
     *  @param  node the right child of this node
     */
     public   void  setRight ( BinaryTreeNode < T >  node )  
     {
        right  =  node ;
     }

     /**
     * Return the left child of this node.
     *
     *  @return  the left child of the node
     */
     public   BinaryTreeNode < T >  getLeft ()  
     {
         return  left ;
     }

     /**
     * Sets the left child of this node.
     *
     *  @param  node the left child of this node
     */
     public   void  setLeft ( BinaryTreeNode < T >  node )  
     {
        left  =  node ;
     }
}

Chap19/ExpressionTrees/jsjf/exceptions/ElementNotFoundException.java

Chap19/ExpressionTrees/jsjf/exceptions/ElementNotFoundException.java

package  jsjf . exceptions ;

/**
 * ElementNotFoundException represents the situation in which a target element 
 * is not present in a collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ElementNotFoundException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     */
     public   ElementNotFoundException   ( String  collection )
     {
         super   ( "The target element is not in this "   +  collection );
     }
}

Chap19/ExpressionTrees/jsjf/exceptions/EmptyCollectionException.java

Chap19/ExpressionTrees/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " is empty." );
     }
}

Chap19/ExpressionTrees/jsjf/exceptions/NonComparableElementException.java

Chap19/ExpressionTrees/jsjf/exceptions/NonComparableElementException.java

package  jsjf . exceptions ;

/**
 * NonComparableElementException  represents the situation in which an attempt 
 * is made to add an element that is not comparable to an ordered collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   NonComparableElementException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     * 
     *  @param  collection  the exception message to deliver
     */
     public   NonComparableElementException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " requires Comparable elements." );
     }
}

Chap19/ExpressionTrees/jsjf/LinkedBinaryTree.java

Chap19/ExpressionTrees/jsjf/LinkedBinaryTree.java

package  jsjf ;

import  java . util . * ;
import  jsjf . exceptions . * ;

/**
 * LinkedBinaryTree implements the BinaryTreeADT interface
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinkedBinaryTree < T >   implements   BinaryTreeADT < T > ,   Iterable < T >
{
     protected   BinaryTreeNode < T >  root ;  
     protected   int  modCount ;

     /**
     * Creates an empty binary tree.
     */
     public   LinkedBinaryTree ()  
     {
        root  =   null ;
     }

     /**
     * Creates a binary tree with the specified element as its root.
     *
     *  @param  element the element that will become the root of the binary tree
     */
     public   LinkedBinaryTree ( T element )  
     {
        root  =   new   BinaryTreeNode < T > ( element );
     }

     /**
     * Creates a binary tree with the specified element as its root and the 
     * given trees as its left child and right child
     *
     *  @param  element the element that will become the root of the binary tree
     *  @param  left the left subtree of this tree
     *  @param  right the right subtree of this tree
     */
     public   LinkedBinaryTree ( T element ,   LinkedBinaryTree < T >  left ,  
             LinkedBinaryTree < T >  right )  
     {
        root  =   new   BinaryTreeNode < T > ( element );
        root . setLeft ( left . root );
        root . setRight ( right . root );
     }

     /**
     * Returns a reference to the element at the root
     *
     *  @return  a reference to the specified target
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T getRootElement ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the node at the root
     *
     *  @return  a reference to the specified node
     *  @throws  EmptyCollectionException if the tree is empty
     */
     protected   BinaryTreeNode < T >  getRootNode ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the left subtree of the root of this tree.
     *
     *  @return  a link to the left subtree fo the tree
     */
     public   LinkedBinaryTree < T >  getLeft ()
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the right subtree of the root of this tree.
     *
     *  @return  a link to the right subtree of the tree
     */
     public   LinkedBinaryTree < T >  getRight ()
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this binary tree is empty and false otherwise.
     *
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ()  
     {
         return   ( root  ==   null );
     }

     /**
     * Returns the integer size of this tree.
     *
     *  @return  the integer size of the tree
     */
     public   int  size ()  
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns the height of this tree.
     *
     *  @return  the height of the tree
     */
     public   int  getHeight ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns the height of the specified node.
     *
     *  @param  node the node from which to calculate the height
     *  @return  the height of the tree
     */
     private   int  height ( BinaryTreeNode < T >  node )  
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns true if this tree contains an element that matches the
     * specified target element and false otherwise.
     *
     *  @param  targetElement the element being sought in this tree
     *  @return  true if the element in is this tree, false otherwise
     */
     public   boolean  contains ( T targetElement )  
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this binary tree.  Throws a ElementNotFoundException if
     * the specified target element is not found in the binary tree.
     *
     *  @param  targetElement the element being sought in this tree
     *  @return  a reference to the specified target
     *  @throws  ElementNotFoundException if the element is not in the tree
     */
     public  T find ( T targetElement )   throws   ElementNotFoundException
     {
         BinaryTreeNode < T >  current  =  findNode ( targetElement ,  root );

         if   ( current  ==   null )
             throw   new   ElementNotFoundException ( "LinkedBinaryTree" );

         return   ( current . getElement ());
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this binary tree.
     *
     *  @param  targetElement the element being sought in this tree
     *  @param  next the element to begin searching from
     */
     private   BinaryTreeNode < T >  findNode ( T targetElement ,  
             BinaryTreeNode < T >  next )
     {
         if   ( next  ==   null )
             return   null ;

         if   ( next . getElement (). equals ( targetElement ))
             return  next ;

         BinaryTreeNode < T >  temp  =  findNode ( targetElement ,  next . getLeft ());

         if   ( temp  ==   null )
            temp  =  findNode ( targetElement ,  next . getRight ());

         return  temp ;
     }

     /**
     * Returns a string representation of this binary tree showing
     * the nodes in an inorder fashion.
     *
     *  @return  a string representation of this binary tree
     */
     public   String  toString ()  
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }

     /**
     * Returns an iterator over the elements in this tree using the 
     * iteratorInOrder method
     *
     *  @return  an in order iterator over this binary tree
     */
     public   Iterator < T >  iterator ()
     {
         return  iteratorInOrder ();
     }

     /**
     * Performs an inorder traversal on this binary tree by calling an
     * overloaded, recursive inorder method that starts with
     * the root.
     *
     *  @return  an in order iterator over this binary tree
     */
     public   Iterator < T >  iteratorInOrder ()
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        inOrder ( root ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive inorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  inOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  !=   null )
         {
            inOrder ( node . getLeft (),  tempList );
            tempList . addToRear ( node . getElement ());
            inOrder ( node . getRight (),  tempList );
         }
     }

     /**
     * Performs an preorder traversal on this binary tree by calling 
     * an overloaded, recursive preorder method that starts with
     * the root.
     *
     *  @return  a pre order iterator over this tree
     */
     public   Iterator < T >  iteratorPreOrder ()  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Performs a recursive preorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  preOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         // To be completed as a Programming Project
     }

     /**
     * Performs an postorder traversal on this binary tree by calling
     * an overloaded, recursive postorder method that starts
     * with the root.
     *
     *  @return  a post order iterator over this tree
     */
     public   Iterator < T >  iteratorPostOrder ()  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Performs a recursive postorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  postOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         // To be completed as a Programming Project
     }

     /**
     * Performs a levelorder traversal on this binary tree, using a
     * templist.
     *
     *  @return  a levelorder iterator over this binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ()  
     {
         ArrayUnorderedList < BinaryTreeNode < T >>  nodes  =  
                 new   ArrayUnorderedList < BinaryTreeNode < T >> ();
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
         BinaryTreeNode < T >  current ;

        nodes . addToRear ( root );

         while   ( ! nodes . isEmpty ())  
         {
            current  =  nodes . removeFirst ();

             if   ( current  !=   null )
             {
                tempList . addToRear ( current . getElement ());
                 if   ( current . getLeft ()   !=   null )
                    nodes . addToRear ( current . getLeft ());
                 if   ( current . getRight ()   !=   null )
                    nodes . addToRear ( current . getRight ());
             }
             else
                tempList . addToRear ( null );
         }

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Inner class to represent an iterator over the elements of this tree
     */
     private   class   TreeIterator   implements   Iterator < T >
     {
         private   int  expectedModCount ;
         private   Iterator < T >  iter ;

         /**
         * Sets up this iterator using the specified iterator.
         *
         *  @param  iter the list iterator created by a tree traversal
         */
         public   TreeIterator ( Iterator < T >  iter )
         {
             this . iter  =  iter ;
            expectedModCount  =  modCount ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( ! ( modCount  ==  expectedModCount ))
                 throw   new   ConcurrentModificationException ();

             return   ( iter . hasNext ());
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return  the next element in the iteration
         *  @throws  NoSuchElementException if the iterator is empty
         */
         public  T next ()   throws   NoSuchElementException
         {
             if   ( hasNext ())
                 return   ( iter . next ());
             else  
                 throw   new   NoSuchElementException ();
         }

         /**
         * The remove operation is not supported.
         * 
         *  @throws  UnsupportedOperationException if the remove operation is called
         */
         public   void  remove ()
         {
             throw   new   UnsupportedOperationException ();
         }
     }
}

Chap19/ExpressionTrees/jsjf/ListADT.java

Chap19/ExpressionTrees/jsjf/ListADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * ListADT defines the interface to a general list collection. Specific
 * types of lists will extend this interface to complete the
 * set of necessary operations.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   ListADT < T >   extends   Iterable < T >
{
     /**  
     * Removes and returns the first element from this list. 
     * 
     *  @return  the first element from this list
     */
     public  T removeFirst ();

     /**  
     * Removes and returns the last element from this list. 
     *
     *  @return  the last element from this list
     */
     public  T removeLast ();

     /**  
     * Removes and returns the specified element from this list. 
     *
     *  @param  element the element to be removed from the list
     */
     public  T remove ( T element );

     /**  
     * Returns a reference to the first element in this list. 
     *
     *  @return  a reference to the first element in this list
     */
     public  T first ();

     /**  
     * Returns a reference to the last element in this list. 
     *
     *  @return  a reference to the last element in this list
     */
     public  T last ();

     /**  
     * Returns true if this list contains the specified target element. 
     *
     *  @param  target the target that is being sought in the list
     *  @return  true if the list contains this element
     */
     public   boolean  contains ( T target );

     /**  
     * Returns true if this list contains no elements. 
     *
     *  @return  true if this list contains no elements
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this list. 
     *
     *  @return  the integer representation of number of elements in this list
     */
     public   int  size ();

     /**  
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements in this list
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns a string representation of this list. 
     *
     *  @return  a string representation of this list
     */
     public   String  toString ();
}

Chap19/ExpressionTrees/jsjf/UnorderedListADT.java

Chap19/ExpressionTrees/jsjf/UnorderedListADT.java

package  jsjf ;

/**
 * UnorderedListADT defines the interface to an unordered list collection. 
 * Elements are stored in any order the user desires.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   UnorderedListADT < T >   extends   ListADT < T >
{
     /**  
     * Adds the specified element to the front of this list. 
     *
     *  @param  element the element to be added to the front of this list    
     */
     public   void  addToFront ( T element );   

     /**  
     * Adds the specified element to the rear of this list. 
     *
     *  @param  element the element to be added to the rear of this list    
     */
     public   void  addToRear ( T element );  

     /**  
     * Adds the specified element after the specified target. 
     *
     *  @param  element the element to be added after the target
     *  @param  target  the target is the item that the element will be added
     *                after    
     */
     public   void  addAfter ( T element ,  T target );
}

Chap19/ExpressionTrees/PostfixEvaluator.java

Chap19/ExpressionTrees/PostfixEvaluator.java

import  java . util . * ;

/**
 * PostfixEvaluator this modification of our stack example uses a 
 * stack to create an expression tree from a VALID integer postfix expression 
 * and then uses a recursive method from the ExpressionTree class to 
 * evaluate the tree.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   PostfixEvaluator     
{
     private   Stack < ExpressionTree >  treeStack ;

     /**
     * Sets up this evaluator by creating a new stack.
     */
     public   PostfixEvaluator ()
     {
        treeStack  =   new   Stack < ExpressionTree > ();
     }

     /**
     * Retrieves and returns the next operand off of this tree stack.
     *
     *  @param  treeStack  the tree stack from which the operand will be returned
     *  @return  the next operand off of this tree stack
     */
     private   ExpressionTree  getOperand ( Stack < ExpressionTree >  treeStack )
     {
         ExpressionTree  temp ;
        temp  =  treeStack . pop ();

         return  temp ;
     }

     /**
     * Evaluates the specified postfix expression by building and evaluating
     * an expression tree. 
     *
     *  @param  expression string representation of a postfix expression
     *  @return  value of the given expression
     */
     public   int  evaluate ( String  expression )
     {
         ExpressionTree  operand1 ,  operand2 ;
         char  operator ;
         String  tempToken ;

         Scanner  parser  =   new   Scanner ( expression );

         while   ( parser . hasNext ())  
         {
            tempToken  =  parser . next ();
            operator  =  tempToken . charAt ( 0 );

             if   (( operator  ==   '+' )   ||   ( operator  ==   '-' )   ||   ( operator  ==   '*' )   ||  
                     ( operator  ==   '/' ))
             {
                operand1  =  getOperand ( treeStack );
                operand2  =  getOperand ( treeStack );
                treeStack . push ( new   ExpressionTree  
                         ( new   ExpressionTreeOp ( 1 , operator , 0 ),  operand2 ,  operand1 ));
             }
             else
             {
                treeStack . push ( new   ExpressionTree ( new   ExpressionTreeOp
                         ( 2 ,   ' ' ,   Integer . parseInt ( tempToken )),   null ,   null ));
             }

         }
         return   ( treeStack . peek ()). evaluateTree ();         
     }

     /**
     * Returns the expression tree associated with this postfix evaluator. 
     *
     *  @return  string representing the expression tree
     */
     public   String  getTree ()
     {
         return   ( treeStack . peek ()). printTree ();
     }
}

Chap19/ExpressionTrees/PostfixTester.java

Chap19/ExpressionTrees/PostfixTester.java

import  java . util . Scanner ;

/**
 * Demonstrates the use of an expression tree to evaluate postfix expressions.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   PostfixTester     
{
     /**
     * Reads and evaluates multiple postfix expressions.
     */
     public   static   void  main ( String []  args )
     {
         String  expression ,  again ;
         int  result ;

         Scanner  in  =   new   Scanner ( System . in );

         do
         {   
             PostfixEvaluator  evaluator  =   new   PostfixEvaluator ();
             System . out . println ( "Enter a valid post-fix expression one token "   +
                     "at a time with a space between each token (e.g. 5 4 + 3 2 1 - + *)" );
             System . out . println ( "Each token must be an integer or an operator (+,-,*,/)" );
            expression  =  in . nextLine ();

            result  =  evaluator . evaluate ( expression );
             System . out . println ();
             System . out . println ( "That expression equals "   +  result );

             System . out . println ( "The Expression Tree for that expression is: " );
             System . out . println ( evaluator . getTree ());

             System . out . print ( "Evaluate another expression [Y/N]? " );
            again  =  in . nextLine ();
             System . out . println ();
         }
         while   ( again . equalsIgnoreCase ( "y" ));
     }
}

Chap20/BinarySearchTreeList/jsjf/ArrayList.java

Chap20/BinarySearchTreeList/jsjf/ArrayList.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . * ;

/**
 * ArrayList represents an array implementation of a list. The front of
 * the list is kept at array index 0. This class will be extended
 * to create a specific kind of list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   abstract   class   ArrayList < T >   implements   ListADT < T > ,   Iterable < T >
{
     private   final   static   int  DEFAULT_CAPACITY  =   100 ;
     private   final   static   int  NOT_FOUND  =   - 1 ;

     protected   int  rear ;
     protected  T []  list ;  
     protected   int  modCount ;

     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayList ()
     {
         this ( DEFAULT_CAPACITY );
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the integer value of the size of the array list
     */
     public   ArrayList ( int  initialCapacity )
     {
        rear  =   0 ;
        list  =   ( T [])( new   Object [ initialCapacity ]);
        modCount  =   0 ;
     }

     /**
     * Creates a new array to store the contents of this list with
     * twice the capacity of the old one. Called by descendant classes
     * that add elements to the list.
     */
     protected   void  expandCapacity ()
     {
         // To be completed as a Programming Project
     }

     /**
     * Removes and returns the last element in this list.
     *
     *  @return  the last element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeLast ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the first element in this list.
     *
     *  @return  the first element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeFirst ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the specified element.
     *
     *  @param   element the element to be removed and returned from the list
     *  @return  the removed elememt
     *  @throws  ElementNotFoundException if the element is not in the list
     */
     public  T remove ( T element )
     {
        T result ;
         int  index  =  find ( element );

         if   ( index  ==  NOT_FOUND )
             throw   new   ElementNotFoundException ( "ArrayList" );

        result  =  list [ index ];
        rear -- ;

         // shift the appropriate elements 
         for   ( int  scan  =  index ;  scan  <  rear ;  scan ++ )
            list [ scan ]   =  list [ scan + 1 ];

        list [ rear ]   =   null ;
        modCount ++ ;

         return  result ;
     }

     /**
     * Returns a reference to the element at the front of this list.
     * The element is not removed from the list.  Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the first element in the list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the element at the rear of this list.
     * The element is not removed from the list. Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the last element of this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T last ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this list contains the specified element.
     *
     *  @param  target the target element
     *  @return  true if the target is in the list, false otherwise 
     */
     public   boolean  contains ( T target )
     {
         return   ( find ( target )   !=  NOT_FOUND );
     }

     /**
     * Returns the array index of the specified element, or the
     * constant NOT_FOUND if it is not found.
     *
     *  @param  target the target element
     *  @return  the index of the target element, or the 
     *         NOT_FOUND constant
     */
     private   int  find ( T target )
     {
         int  scan  =   0 ;  
         int  result  =  NOT_FOUND ;

         if   ( ! isEmpty ())
             while   ( result  ==  NOT_FOUND  &&  scan  <  rear )
                 if   ( target . equals ( list [ scan ]))
                    result  =  scan ;
                 else
                    scan ++ ;

         return  result ;
     }

     /**
     * Returns true if this list is empty and false otherwise. 
     *
     *  @return  true if the list is empty, false otherwise
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements currently in this list.
     *
     *  @return  the number of elements in the list
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this list. 
     * 
     *  @return  the string representation of the list
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }

     /**
     * Returns an iterator for the elements currently in this list.
     * 
     *  @return  an iterator for the elements in the list
     */
     public   Iterator < T >  iterator ()
     {
         return   new   ArrayListIterator ();
     }

     /**
     * ArrayListIterator iterator over the elements of an ArrayList.
     */  
     private   class   ArrayListIterator   implements   Iterator < T >
     {
         int  iteratorModCount ;
         int  current ;

         /**
         * Sets up this iterator using the specified modCount.
         * 
         *  @param  modCount the current modification count for the ArrayList
         */
         public   ArrayListIterator ()
         {
            iteratorModCount  =  modCount ;
            current  =   0 ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( iteratorModCount  !=  modCount )
                 throw   new   ConcurrentModificationException ();

             return   ( current  <  rear );
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return   the next element in the iteration
         *  @throws   NoSuchElementException if an element not found exception occurs
         *  @throws   ConcurrentModificationException if the collection has changed
         */
         public  T next ()   throws   ConcurrentModificationException
         {
             if   ( ! hasNext ())
                 throw   new   NoSuchElementException ();

            current ++ ;

             return  list [ current  -   1 ];
         }

         /**
         * The remove operation is not supported in this collection.
         * 
         *  @throws  UnsupportedOperationException if the remove method is called
         */
         public   void  remove ()   throws   UnsupportedOperationException
         {
             throw   new   UnsupportedOperationException ();
         }

     }    
}

Chap20/BinarySearchTreeList/jsjf/ArrayUnorderedList.java

Chap20/BinarySearchTreeList/jsjf/ArrayUnorderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayUnorderedList represents an array implementation of an unordered list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayUnorderedList < T >   extends   ArrayList < T >  
implements   UnorderedListADT < T >
{
     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayUnorderedList ()
     {
         super ();
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the initial size of the list
     */
     public   ArrayUnorderedList ( int  initialCapacity )
     {
         super ( initialCapacity );
     }

     /**
     * Adds the specified element to the front of this list.
     * 
     *  @param  element the element to be added to the front of the list
     */
     public   void  addToFront ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element to the rear of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToRear ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element after the specified target element.
     * Throws an ElementNotFoundException if the target is not found.
     *
     *  @param  element the element to be added after the target element
     *  @param  target  the target that the element is to be added after
     */
     public   void  addAfter ( T element ,  T target )
     {
         if   ( size ()   ==  list . length )
            expandCapacity ();

         int  scan  =   0 ;

         // find the insertion point
         while   ( scan  <  rear  &&   ! target . equals ( list [ scan ]))  
            scan ++ ;

         if   ( scan  ==  rear )
             throw   new   ElementNotFoundException ( "UnorderedList" );

        scan ++ ;

         // shift elements up one
         for   ( int  shift  =  rear ;  shift  >  scan ;  shift -- )
            list [ shift ]   =  list [ shift  -   1 ];

         // insert element
        list [ scan ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }
}

Chap20/BinarySearchTreeList/jsjf/BinarySearchTreeADT.java

Chap20/BinarySearchTreeList/jsjf/BinarySearchTreeADT.java

package  jsjf ;

/**
 * BinarySearchTreeADT defines the interface to a binary search tree.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   BinarySearchTreeADT < T >   extends   BinaryTreeADT < T >  
{
     /** 
     * Adds the specified element to the proper location in this tree. 
     *
     *  @param  element the element to be added to this tree
     */
     public   void  addElement ( T element );

     /** 
     * Removes and returns the specified element from this tree. 
     *
     *  @param  targetElement the element to be removed from the tree
     *  @return  the element to be removed from the tree
     */  
     public  T removeElement ( T targetElement );

     /** 
     * Removes all occurences of the specified element from this tree. 
     *
     *  @param  targetElement the element to be removed from the tree
     */
     public   void  removeAllOccurrences ( T targetElement );

     /** 
     * Removes and returns the smallest element from this tree. 
     *
     *  @return  the smallest element from the tree.
     */
     public  T removeMin ();

     /** 
     * Removes and returns the largest element from this tree. 
     *
     *  @return  the largest element from the tree
     */  
     public  T removeMax ();

     /** 
     * Returns the smallest element in this tree without removing it. 
     * 
     *  @return  the smallest element in the tree
     */  
     public  T findMin ();

     /** 
     * Returns the largest element in this tree without removing it. 
     * 
     *  @return  the largest element in the tree
     */
     public  T findMax ();
}


Chap20/BinarySearchTreeList/jsjf/BinarySearchTreeList.java

Chap20/BinarySearchTreeList/jsjf/BinarySearchTreeList.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * BinarySearchTreeList represents an ordered list implemented using a binary
 * search tree.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   BinarySearchTreeList < T >   extends   LinkedBinarySearchTree < T >  
implements   ListADT < T > ,   OrderedListADT < T > ,   Iterable < T >
{
     /**
     * Creates an empty BinarySearchTreeList.
     */
     public   BinarySearchTreeList ()  
     {
         super ();
     }

     /**
     * Adds the given element to this list.
     * 
     *  @param  element the element to be added to the list
     */
     public   void  add ( T element )
     {
        addElement ( element );
     }

     /**
     * Removes and returns the first element from this list.
     *
     *  @return  the first element in the list
     */
     public  T removeFirst ()
     {
         return  removeMin ();
     }

     /**
     * Removes and returns the last element from this list.
     *
     *  @return  the last element from the list
     */
     public  T removeLast ()
     {
         return  removeMax ();
     }

     /**
     * Removes and returns the specified element from this list.
     *
     *  @param  element the element being sought in the list
     *  @return  the element from the list that matches the target
     */
     public  T remove ( T element )
     {
         return  removeElement ( element );
     }

     /**
     * Returns a reference to the first element on this list.
     *
     *  @return  a reference to the first element in the list
     */
     public  T first ()
     {
         return  findMin ();
     }

     /**
     * Returns a reference to the last element on this list.
     *
     *  @return  a reference to the last element in the list
     */
     public  T last ()
     {
         return  findMax ();
     }

     /**
     * Returns an iterator for the list.
     *
     *  @return  an iterator over the elements in the list
     */
     public   Iterator < T >  iterator ()
     {
         return  iteratorInOrder ();
     }
}

Chap20/BinarySearchTreeList/jsjf/BinaryTreeADT.java

Chap20/BinarySearchTreeList/jsjf/BinaryTreeADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * BinaryTreeADT defines the interface to a binary tree data structure.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   BinaryTreeADT < T >  
{
     /** 
     * Returns a reference to the root element 
     *
     *  @return  a reference to the root
     */
     public  T getRootElement ();

     /** 
     * Returns true if this binary tree is empty and false otherwise.
     *
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ();

     /** 
     * Returns the number of elements in this binary tree.
     *
     *  @return  the number of elements in the tree
     */
     public   int  size ();

     /** 
     * Returns true if the binary tree contains an element that matches
     * the specified element and false otherwise. 
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the tree contains the target element
     */
     public   boolean  contains ( T targetElement );

     /** 
     * Returns a reference to the specified element if it is found in 
     * this binary tree. Throws an exception if the specified element
     * is not found.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  a reference to the specified element
     */
     public  T find ( T targetElement );

     /**  
     * Returns the string representation of this binary tree.
     *
     *  @return  a string representation of the binary tree
     */
     public   String  toString ();

     /**  
     * Returns an iterator over the elements of this tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns an iterator that represents an inorder traversal on this binary tree.  
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorInOrder ();

     /**  
     * Returns an iterator that represents a preorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPreOrder ();

     /**  
     * Returns an iterator that represents a postorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPostOrder ();

     /**  
     * Returns an iterator that represents a levelorder traversal on the binary tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ();
}

Chap20/BinarySearchTreeList/jsjf/BinaryTreeNode.java

Chap20/BinarySearchTreeList/jsjf/BinaryTreeNode.java

package  jsjf ;

/**
 * BinaryTreeNode represents a node in a binary tree with a left and 
 * right child.
 * 
 * Solution to Programming Project 19.3 (isLeaf method)
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   BinaryTreeNode < T >
{
     protected  T element ;
     protected   BinaryTreeNode < T >  left ,  right ;

     /**
     * Creates a new tree node with the specified data.
     *
     *  @param  obj the element that will become a part of the new tree node
     */
     public   BinaryTreeNode ( T obj )  
     {
        element  =  obj ;
        left  =   null ;
        right  =   null ;
     }

     /**
     * Creates a new tree node with the specified data.
     *
     *  @param  obj the element that will become a part of the new tree node
     *  @param  left the tree that will be the left subtree of this node
     *  @param  right the tree that will be the right subtree of this node
     */
     public   BinaryTreeNode ( T obj ,   LinkedBinaryTree < T >  left ,   LinkedBinaryTree < T >  right )  
     {
        element  =  obj ;
         if   ( left  ==   null )
             this . left  =   null ;
         else
             this . left  =  left . getRootNode ();

         if   ( right  ==   null )
             this . right  =   null ;
         else
             this . right  =  right . getRootNode ();
     }

     /**
     * Returns the number of non-null children of this node.
     *
     *  @return  the integer number of non-null children of this node 
     */
     public   int  numChildren ()  
     {
         int  children  =   0 ;

         if   ( left  !=   null )
            children  =   1   +  left . numChildren ();

         if   ( right  !=   null )
            children  =  children  +   1   +  right . numChildren ();

         return  children ;
     }

     /**
     * Return true if this node is a leaf and false otherwise.
     *
     *  @return  true if this node is a leaf and false otherwise
     */
     public   boolean  isLeaf ()  
     {
         return   ( numChildren ()   ==   0 );
     }

     /**
     * Return the element at this node.
     *
     *  @return  the element stored at this node
     */
     public  T getElement ()  
     {
         return  element ;
     }

     /**
     * Return the right child of this node.
     *
     *  @return  the right child of this node
     */
     public   BinaryTreeNode < T >  getRight ()  
     {
         return  right ;
     }

     /**
     * Sets the right child of this node.
     *
     *  @param  node the right child of this node
     */
     public   void  setRight ( BinaryTreeNode < T >  node )  
     {
        right  =  node ;
     }

     /**
     * Return the left child of this node.
     *
     *  @return  the left child of the node
     */
     public   BinaryTreeNode < T >  getLeft ()  
     {
         return  left ;
     }

     /**
     * Sets the left child of this node.
     *
     *  @param  node the left child of this node
     */
     public   void  setLeft ( BinaryTreeNode < T >  node )  
     {
        left  =  node ;
     }
}

Chap20/BinarySearchTreeList/jsjf/exceptions/ElementNotFoundException.java

Chap20/BinarySearchTreeList/jsjf/exceptions/ElementNotFoundException.java

package  jsjf . exceptions ;

/**
 * ElementNotFoundException represents the situation in which a target element 
 * is not present in a collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ElementNotFoundException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     */
     public   ElementNotFoundException   ( String  collection )
     {
         super   ( "The target element is not in this "   +  collection );
     }
}

Chap20/BinarySearchTreeList/jsjf/exceptions/EmptyCollectionException.java

Chap20/BinarySearchTreeList/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " is empty." );
     }
}

Chap20/BinarySearchTreeList/jsjf/exceptions/NonComparableElementException.java

Chap20/BinarySearchTreeList/jsjf/exceptions/NonComparableElementException.java

package  jsjf . exceptions ;

/**
 * NonComparableElementException  represents the situation in which an attempt 
 * is made to add an element that is not comparable to an ordered collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   NonComparableElementException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     * 
     *  @param  collection  the exception message to deliver
     */
     public   NonComparableElementException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " requires Comparable elements." );
     }
}

Chap20/BinarySearchTreeList/jsjf/LinkedBinarySearchTree.java

Chap20/BinarySearchTreeList/jsjf/LinkedBinarySearchTree.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * LinkedBinarySearchTree implements the BinarySearchTreeADT interface 
 * with links.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinkedBinarySearchTree < T >   extends   LinkedBinaryTree < T >
implements   BinarySearchTreeADT < T >
{
     /**
     * Creates an empty binary search tree.
     */
     public   LinkedBinarySearchTree ()  
     {
         super ();
     }

     /**
     * Creates a binary search with the specified element as its root.
     *
     *  @param  element the element that will be the root of the new binary
     *        search tree
     */
     public   LinkedBinarySearchTree ( T element )  
     {
         super ( element );

         if   ( ! ( element  instanceof   Comparable ))
             throw   new   NonComparableElementException ( "LinkedBinarySearchTree" );
     }

     /**
     * Adds the specified object to the binary search tree in the
     * appropriate position according to its natural order.  Note that
     * equal elements are added to the right.
     *
     *  @param  element the element to be added to the binary search tree
     */
     public   void  addElement ( T element )  
     {
         if   ( ! ( element  instanceof   Comparable ))
             throw   new   NonComparableElementException ( "LinkedBinarySearchTree" );

         Comparable < T >  comparableElement  =   ( Comparable < T > ) element ;

         if   ( isEmpty ())
            root  =   new   BinaryTreeNode < T > ( element );
         else  
         {
             if   ( comparableElement . compareTo ( root . getElement ())   <   0 )
             {
                 if   ( root . getLeft ()   ==   null )  
                     this . getRootNode (). setLeft ( new   BinaryTreeNode < T > ( element ));
                 else
                    addElement ( element ,  root . getLeft ());
             }
             else
             {
                 if   ( root . getRight ()   ==   null )  
                     this . getRootNode (). setRight ( new   BinaryTreeNode < T > ( element ));
                 else
                    addElement ( element ,  root . getRight ());
             }
         }
        modCount ++ ;
     }

     /**
     * Adds the specified object to the binary search tree in the
     * appropriate position according to its natural order.  Note that
     * equal elements are added to the right.
     *
     *  @param  element the element to be added to the binary search tree
     */
     private   void  addElement ( T element ,   BinaryTreeNode < T >  node )  
     {
         Comparable < T >  comparableElement  =   ( Comparable < T > ) element ;

         if   ( comparableElement . compareTo ( node . getElement ())   <   0 )
         {
             if   ( node . getLeft ()   ==   null )  
                node . setLeft ( new   BinaryTreeNode < T > ( element ));
             else
                addElement ( element ,  node . getLeft ());
         }
         else
         {
             if   ( node . getRight ()   ==   null )  
                node . setRight ( new   BinaryTreeNode < T > ( element ));
             else
                addElement ( element ,  node . getRight ());
         }
     }


     /**
     * Removes the first element that matches the specified target
     * element from the binary search tree and returns a reference to
     * it.  Throws a ElementNotFoundException if the specified target
     * element is not found in the binary search tree.
     *
     *  @param  targetElement the element being sought in the binary search tree
     *  @throws  ElementNotFoundException if the target element is not found
     */
     public  T removeElement ( T targetElement )
             throws   ElementNotFoundException  
     {
        T result  =   null ;

         if   ( isEmpty ())
             throw   new   ElementNotFoundException ( "LinkedBinarySearchTree" );
         else
         {
             BinaryTreeNode < T >  parent  =   null ;
             if   ((( Comparable < T > ) targetElement ). equals ( root . element ))  
             {
                result  =   root . element ;
                 BinaryTreeNode < T >  temp  =  replacement ( root );
                 if   ( temp  ==   null )
                    root  =   null ;
                 else  
                 {
                    root . element  =  temp . element ;
                    root . setRight ( temp . right );
                    root . setLeft ( temp . left );
                 }

                modCount -- ;
             }
             else  
             {                 
                parent  =  root ;
                 if   ((( Comparable ) targetElement ). compareTo ( root . element )   <   0 )
                    result  =  removeElement ( targetElement ,  root . getLeft (),  parent );
                 else
                    result  =  removeElement ( targetElement ,  root . getRight (),  parent );
             }
         }

         return  result ;
     }

     /**
     * Removes the first element that matches the specified target
     * element from the binary search tree and returns a reference to
     * it.  Throws a ElementNotFoundException if the specified target
     * element is not found in the binary search tree.
     *
     *  @param  targetElement the element being sought in the binary search tree
     *  @param  node the node from which to search
     *  @param  parent the parent of the node from which to search
     *  @throws  ElementNotFoundException if the target element is not found
     */
     private  T removeElement ( T targetElement ,   BinaryTreeNode < T >  node ,   BinaryTreeNode < T >  parent )
             throws   ElementNotFoundException  
     {
        T result  =   null ;

         if   ( node  ==   null )
             throw   new   ElementNotFoundException ( "LinkedBinarySearchTree" );
         else
         {
             if   ((( Comparable < T > ) targetElement ). equals ( node . element ))  
             {
                result  =   node . element ;
                 BinaryTreeNode < T >  temp  =  replacement ( node );
                 if   ( parent . right  ==  node )
                    parent . right  =  temp ;
                 else  
                    parent . left  =  temp ;

                modCount -- ;
             }
             else  
             {                 
                parent  =  node ;
                 if   ((( Comparable ) targetElement ). compareTo ( node . element )   <   0 )
                    result  =  removeElement ( targetElement ,  node . getLeft (),  parent );
                 else
                    result  =  removeElement ( targetElement ,  node . getRight (),  parent );
             }
         }

         return  result ;
     }

     /**
     * Returns a reference to a node that will replace the one
     * specified for removal. In the case where the removed node has 
     * two children, the inorder successor is used as its replacement.
     *
     *  @param  node the node to be removed
     *  @return  a reference to the replacing node
     */
     private   BinaryTreeNode < T >  replacement ( BinaryTreeNode < T >  node )  
     {
         BinaryTreeNode < T >  result  =   null ;

         if   (( node . left  ==   null )   &&   ( node . right  ==   null ))
            result  =   null ;

         else   if   (( node . left  !=   null )   &&   ( node . right  ==   null ))
            result  =  node . left ;

         else   if   (( node . left  ==   null )   &&   ( node . right  !=   null ))
            result  =  node . right ;

         else
         {
             BinaryTreeNode < T >  current  =  node . right ;
             BinaryTreeNode < T >  parent  =  node ;

             while   ( current . left  !=   null )
             {
                parent  =  current ;
                current  =  current . left ;
             }

            current . left  =  node . left ;
             if   ( node . right  !=  current )
             {
                parent . left  =  current . right ;
                current . right  =  node . right ;
             }

            result  =  current ;
         }

         return  result ;
     }

     /**
     * Removes elements that match the specified target element from 
     * the binary search tree. Throws a ElementNotFoundException if 
     * the sepcified target element is not found in this tree.
     *
     *  @param  targetElement the element being sought in the binary search tree
     *  @throws  ElementNotFoundException if the target element is not found
     */
     public   void  removeAllOccurrences ( T targetElement )
             throws   ElementNotFoundException  
     {
        removeElement ( targetElement );

         try
         {
             while   ( contains (( T ) targetElement ))
                removeElement ( targetElement );
         }

         catch   ( Exception   ElementNotFoundException )
         {
         }
     }

     /**
     * Removes the node with the least value from the binary search
     * tree and returns a reference to its element.  Throws an
     * EmptyCollectionException if this tree is empty. 
     *
     *  @return  a reference to the node with the least value
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T removeMin ()   throws   EmptyCollectionException  
     {
        T result  =   null ;

         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "LinkedBinarySearchTree" );
         else  
         {
             if   ( root . left  ==   null )  
             {
                result  =  root . element ;
                root  =  root . right ;
             }
             else  
             {
                 BinaryTreeNode < T >  parent  =  root ;
                 BinaryTreeNode < T >  current  =  root . left ;
                 while   ( current . left  !=   null )  
                 {
                    parent  =  current ;
                    current  =  current . left ;
                 }
                result  =   current . element ;
                parent . left  =  current . right ;
             }

            modCount -- ;
         }

         return  result ;
     }

     /**
     * Removes the node with the highest value from the binary
     * search tree and returns a reference to its element.  Throws an
     * EmptyCollectionException if this tree is empty. 
     *
     *  @return  a reference to the node with the highest value
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T removeMax ()   throws   EmptyCollectionException  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the element with the least value in the binary search
     * tree. It does not remove the node from the binary search tree. 
     * Throws an EmptyCollectionException if this tree is empty.
     *
     *  @return  the element with the least value
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T findMin ()   throws   EmptyCollectionException  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the element with the highest value in the binary
     * search tree.  It does not remove the node from the binary
     * search tree.  Throws an EmptyCollectionException if this 
     * tree is empty.
     *
     *  @return  the element with the highest value
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T findMax ()   throws   EmptyCollectionException  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in the binary tree.  Throws a NoSuchElementException if
     * the specified target element is not found in this tree.
     *
     *  @param  targetElement the element being sough in the binary tree
     *  @throws  ElementNotFoundException if the target element is not found
     */
     public  T find ( T targetElement )   throws   ElementNotFoundException  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the left subtree of the root of this tree.
     *
     *  @return  a link to the left subtree fo the tree
     */
     public   LinkedBinarySearchTree < T >  getLeft ()
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the right subtree of the root of this tree.
     *
     *  @return  a link to the right subtree of the tree
     */
     public   LinkedBinarySearchTree < T >  getRight ()
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this tree.  
     *
     *  @param  targetElement the element being sought in the tree
     *  @param  next the tree node to begin searching on
     */
     private   BinaryTreeNode < T >  findNode ( T targetElement ,   BinaryTreeNode < T >  next )  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }
}

Chap20/BinarySearchTreeList/jsjf/LinkedBinaryTree.java

Chap20/BinarySearchTreeList/jsjf/LinkedBinaryTree.java

package  jsjf ;

import  java . util . * ;
import  jsjf . exceptions . * ;

/**
 * LinkedBinaryTree implements the BinaryTreeADT interface.
 * 
 * Solution to Programming Projects 19.1, 19.2, 19.5, 19.7
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinkedBinaryTree < T >   implements   BinaryTreeADT < T > ,   Iterable < T >
{
     protected   BinaryTreeNode < T >  root ;  
     protected   int  modCount ;

     /**
     * Creates an empty binary tree.
     */
     public   LinkedBinaryTree ()  
     {
        root  =   null ;
     }

     /**
     * Creates a binary tree with the specified element as its root.
     *
     *  @param  element the element that will become the root of the binary tree
     */
     public   LinkedBinaryTree ( T element )  
     {
        root  =   new   BinaryTreeNode < T > ( element );
     }

     /**
     * Creates a binary tree with the specified element as its root and the 
     * given trees as its left child and right child
     *
     *  @param  element the element that will become the root of the binary tree
     *  @param  left the left subtree of this tree
     *  @param  right the right subtree of this tree
     */
     public   LinkedBinaryTree ( T element ,   LinkedBinaryTree < T >  left ,  
             LinkedBinaryTree < T >  right )  
     {
        root  =   new   BinaryTreeNode < T > ( element );
        root . setLeft ( left . root );
        root . setRight ( right . root );
     }

     /**
     * Returns a reference to the element at the root
     *
     *  @return  a reference to the specified target
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T getRootElement ()   throws   EmptyCollectionException
     {
         if   ( root  ==   null )
             throw   new   EmptyCollectionException ( "LinkedBinaryTree" );
        
         return   ( root . getElement ());
     }

     /**
     * Returns a reference to the node at the root
     *
     *  @return  a reference to the specified node
     *  @throws  EmptyCollectionException if the tree is empty
     */
     protected   BinaryTreeNode < T >  getRootNode ()   throws   EmptyCollectionException
     {
         if   ( root  ==   null )
             throw   new   EmptyCollectionException ( "LinkedBinaryTree" );
        
         return   ( root );
     }

     /**
     * Returns the left subtree of the root of this tree.
     *
     *  @return  a link to the left subtree of the tree
     */
     public   LinkedBinaryTree < T >  getLeft ()
     {
         if   ( root  ==   null )
             throw   new   EmptyCollectionException ( "Get left operation "
                     +   "failed. The tree is empty." );

         LinkedBinaryTree < T >  result  =   new   LinkedBinaryTree < T > ();
        result . root  =  root . getLeft ();
        
         return  result ;
     }

     /**
     * Returns the right subtree of the root of this tree.
     *
     *  @return  a link to the right subtree of the tree
     */
     public   LinkedBinaryTree < T >  getRight ()
     {
         if   ( root  ==   null )
             throw   new   EmptyCollectionException ( "Get right operation "
                     +   "failed. The tree is empty." );

         LinkedBinaryTree < T >  result  =   new   LinkedBinaryTree < T > ();
        result . root  =  root . getRight ();

         return  result ;
     }

     /**
     * Returns true if this binary tree is empty and false otherwise.
     *
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ()  
     {
         return   ( root  ==   null );
     }

     /**
     * Returns the integer size of this tree.
     *
     *  @return  the integer size of the tree
     */
     public   int  size ()  
     {
         return  root . numChildren ()   +   1 ;
     }

     /**
     * Returns the height of this tree.
     *
     *  @return  the height of the tree
     */
     public   int  getHeight ()
     {
         return  height ( root )   -   1 ;
     }

     /**
     * Returns the height of the specified node.
     *
     *  @param  node the node from which to calculate the height
     *  @return  the height of the tree
     */
     private   int  height ( BinaryTreeNode < T >  node )  
     {
         int  result  =   0 ;
         if   ( node  !=   null )
            result  =   Math . max ( height ( node . getLeft ()),  height ( node . getRight ()))   +   1 ;

         return  result ;
     }

     /**
     * Returns true if this tree contains an element that matches the
     * specified target element and false otherwise.
     *
     *  @param  targetElement the element being sought in this tree
     *  @return  true if the element in is this tree, false otherwise
     */
     public   boolean  contains ( T targetElement )  
     {
        T temp ;
         boolean  found  =   false ;
        
         try  
         {
            temp  =  find ( targetElement );
            found  =   true ;
         }
         catch   ( Exception   ElementNotFoundException )  
         {
            found  =   false ;
         }
        
         return  found ;
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this binary tree.  Throws a ElementNotFoundException if
     * the specified target element is not found in the binary tree.
     *
     *  @param  targetElement the element being sought in this tree
     *  @return  a reference to the specified target
     *  @throws  ElementNotFoundException if the element is not in the tree
     */
     public  T find ( T targetElement )   throws   ElementNotFoundException
     {
         BinaryTreeNode < T >  current  =  findNode ( targetElement ,  root );

         if   ( current  ==   null )
             throw   new   ElementNotFoundException ( "LinkedBinaryTree" );

         return   ( current . getElement ());
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this binary tree.
     *
     *  @param  targetElement the element being sought in this tree
     *  @param  next the element to begin searching from
     */
     private   BinaryTreeNode < T >  findNode ( T targetElement ,  
             BinaryTreeNode < T >  next )
     {
         if   ( next  ==   null )
             return   null ;

         if   ( next . getElement (). equals ( targetElement ))
             return  next ;

         BinaryTreeNode < T >  temp  =  findNode ( targetElement ,  next . getLeft ());

         if   ( temp  ==   null )
            temp  =  findNode ( targetElement ,  next . getRight ());

         return  temp ;
     }

     /**
     * Returns a string representation of this binary tree showing
     * the nodes in an inorder fashion.
     *
     *  @return  a string representation of this binary tree
     */
     public   String  toString ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        inOrder ( root ,  tempList );
        
         return  tempList . toString ();
     }

     /**
     * Returns an iterator over the elements in this tree using the 
     * iteratorInOrder method
     *
     *  @return  an in order iterator over this binary tree
     */
     public   Iterator < T >  iterator ()
     {
         return  iteratorInOrder ();
     }

     /**
     * Performs an inorder traversal on this binary tree by calling an
     * overloaded, recursive inorder method that starts with
     * the root.
     *
     *  @return  an in order iterator over this binary tree
     */
     public   Iterator < T >  iteratorInOrder ()
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        inOrder ( root ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive inorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  inOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  !=   null )
         {
            inOrder ( node . getLeft (),  tempList );
            tempList . addToRear ( node . getElement ());
            inOrder ( node . getRight (),  tempList );
         }
     }

     /**
     * Performs an preorder traversal on this binary tree by calling 
     * an overloaded, recursive preorder method that starts with
     * the root.
     *
     *  @return  a pre order iterator over this tree
     */
     public   Iterator < T >  iteratorPreOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        preOrder ( root ,  tempList );
        
         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive preorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  preOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  !=   null )
         {
            tempList . addToRear ( node . getElement ());
            preOrder ( node . getLeft (),  tempList );
            preOrder ( node . getRight (),  tempList );
         }
     }

     /**
     * Performs an postorder traversal on this binary tree by calling
     * an overloaded, recursive postorder method that starts
     * with the root.
     *
     *  @return  a post order iterator over this tree
     */
     public   Iterator < T >  iteratorPostOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        postOrder ( root ,  tempList );
        
         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive postorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  postOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  !=   null )
         {
            postOrder ( node . getLeft (),  tempList );
            postOrder ( node . getRight (),  tempList );
            tempList . addToRear ( node . getElement ());
         }
     }

     /**
     * Performs a levelorder traversal on this binary tree, using a
     * templist.
     *
     *  @return  a levelorder iterator over this binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ()  
     {
         ArrayUnorderedList < BinaryTreeNode < T >>  nodes  =  
                 new   ArrayUnorderedList < BinaryTreeNode < T >> ();
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
         BinaryTreeNode < T >  current ;

        nodes . addToRear ( root );

         while   ( ! nodes . isEmpty ())  
         {
            current  =  nodes . removeFirst ();

             if   ( current  !=   null )
             {
                tempList . addToRear ( current . getElement ());
                 if   ( current . getLeft ()   !=   null )
                    nodes . addToRear ( current . getLeft ());
                 if   ( current . getRight ()   !=   null )
                    nodes . addToRear ( current . getRight ());
             }
             else
                tempList . addToRear ( null );
         }

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Inner class to represent an iterator over the elements of this tree
     */
     private   class   TreeIterator   implements   Iterator < T >
     {
         private   int  expectedModCount ;
         private   Iterator < T >  iter ;

         /**
         * Sets up this iterator using the specified iterator.
         *
         *  @param  iter the list iterator created by a tree traversal
         */
         public   TreeIterator ( Iterator < T >  iter )
         {
             this . iter  =  iter ;
            expectedModCount  =  modCount ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( ! ( modCount  ==  expectedModCount ))
                 throw   new   ConcurrentModificationException ();

             return   ( iter . hasNext ());
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return  the next element in the iteration
         *  @throws  NoSuchElementException if the iterator is empty
         */
         public  T next ()   throws   NoSuchElementException
         {
             if   ( hasNext ())
                 return   ( iter . next ());
             else  
                 throw   new   NoSuchElementException ();
         }

         /**
         * The remove operation is not supported.
         * 
         *  @throws  UnsupportedOperationException if the remove operation is called
         */
         public   void  remove ()
         {
             throw   new   UnsupportedOperationException ();
         }
     }
}

Chap20/BinarySearchTreeList/jsjf/ListADT.java

Chap20/BinarySearchTreeList/jsjf/ListADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * ListADT defines the interface to a general list collection. Specific
 * types of lists will extend this interface to complete the
 * set of necessary operations.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   ListADT < T >   extends   Iterable < T >
{
     /**  
     * Removes and returns the first element from this list. 
     * 
     *  @return  the first element from this list
     */
     public  T removeFirst ();

     /**  
     * Removes and returns the last element from this list. 
     *
     *  @return  the last element from this list
     */
     public  T removeLast ();

     /**  
     * Removes and returns the specified element from this list. 
     *
     *  @param  element the element to be removed from the list
     */
     public  T remove ( T element );

     /**  
     * Returns a reference to the first element in this list. 
     *
     *  @return  a reference to the first element in this list
     */
     public  T first ();

     /**  
     * Returns a reference to the last element in this list. 
     *
     *  @return  a reference to the last element in this list
     */
     public  T last ();

     /**  
     * Returns true if this list contains the specified target element. 
     *
     *  @param  target the target that is being sought in the list
     *  @return  true if the list contains this element
     */
     public   boolean  contains ( T target );

     /**  
     * Returns true if this list contains no elements. 
     *
     *  @return  true if this list contains no elements
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this list. 
     *
     *  @return  the integer representation of number of elements in this list
     */
     public   int  size ();

     /**  
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements in this list
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns a string representation of this list. 
     *
     *  @return  a string representation of this list
     */
     public   String  toString ();
}

Chap20/BinarySearchTreeList/jsjf/OrderedListADT.java

Chap20/BinarySearchTreeList/jsjf/OrderedListADT.java

package  jsjf ;

/**
 * OrderedListADT defines the interface to an ordered list collection. Only
 * Comparable elements are stored, kept in the order determined by
 * the inherent relationship among the elements.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   OrderedListADT < T >   extends   ListADT < T >
{
     /**
     * Adds the specified element to this list at the proper location
     *
     *  @param  element the element to be added to this list
     */
     public   void  add ( T element );
}

Chap20/BinarySearchTreeList/jsjf/UnorderedListADT.java

Chap20/BinarySearchTreeList/jsjf/UnorderedListADT.java

package  jsjf ;

/**
 * UnorderedListADT defines the interface to an unordered list collection. 
 * Elements are stored in any order the user desires.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   UnorderedListADT < T >   extends   ListADT < T >
{
     /**  
     * Adds the specified element to the front of this list. 
     *
     *  @param  element the element to be added to the front of this list    
     */
     public   void  addToFront ( T element );   

     /**  
     * Adds the specified element to the rear of this list. 
     *
     *  @param  element the element to be added to the rear of this list    
     */
     public   void  addToRear ( T element );  

     /**  
     * Adds the specified element after the specified target. 
     *
     *  @param  element the element to be added after the target
     *  @param  target  the target is the item that the element will be added
     *                after    
     */
     public   void  addAfter ( T element ,  T target );
}

Chap20/LinkedBinarySearchTree/jsjf/ArrayList.java

Chap20/LinkedBinarySearchTree/jsjf/ArrayList.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . * ;

/**
 * ArrayList represents an array implementation of a list. The front of
 * the list is kept at array index 0. This class will be extended
 * to create a specific kind of list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   abstract   class   ArrayList < T >   implements   ListADT < T > ,   Iterable < T >
{
     private   final   static   int  DEFAULT_CAPACITY  =   100 ;
     private   final   static   int  NOT_FOUND  =   - 1 ;

     protected   int  rear ;
     protected  T []  list ;  
     protected   int  modCount ;

     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayList ()
     {
         this ( DEFAULT_CAPACITY );
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the integer value of the size of the array list
     */
     public   ArrayList ( int  initialCapacity )
     {
        rear  =   0 ;
        list  =   ( T [])( new   Object [ initialCapacity ]);
        modCount  =   0 ;
     }

     /**
     * Creates a new array to store the contents of this list with
     * twice the capacity of the old one. Called by descendant classes
     * that add elements to the list.
     */
     protected   void  expandCapacity ()
     {
         // To be completed as a Programming Project
     }

     /**
     * Removes and returns the last element in this list.
     *
     *  @return  the last element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeLast ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the first element in this list.
     *
     *  @return  the first element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeFirst ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the specified element.
     *
     *  @param   element the element to be removed and returned from the list
     *  @return  the removed elememt
     *  @throws  ElementNotFoundException if the element is not in the list
     */
     public  T remove ( T element )
     {
        T result ;
         int  index  =  find ( element );

         if   ( index  ==  NOT_FOUND )
             throw   new   ElementNotFoundException ( "ArrayList" );

        result  =  list [ index ];
        rear -- ;

         // shift the appropriate elements 
         for   ( int  scan  =  index ;  scan  <  rear ;  scan ++ )
            list [ scan ]   =  list [ scan + 1 ];

        list [ rear ]   =   null ;
        modCount ++ ;

         return  result ;
     }

     /**
     * Returns a reference to the element at the front of this list.
     * The element is not removed from the list.  Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the first element in the list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the element at the rear of this list.
     * The element is not removed from the list. Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the last element of this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T last ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this list contains the specified element.
     *
     *  @param  target the target element
     *  @return  true if the target is in the list, false otherwise 
     */
     public   boolean  contains ( T target )
     {
         return   ( find ( target )   !=  NOT_FOUND );
     }

     /**
     * Returns the array index of the specified element, or the
     * constant NOT_FOUND if it is not found.
     *
     *  @param  target the target element
     *  @return  the index of the target element, or the 
     *         NOT_FOUND constant
     */
     private   int  find ( T target )
     {
         int  scan  =   0 ;  
         int  result  =  NOT_FOUND ;

         if   ( ! isEmpty ())
             while   ( result  ==  NOT_FOUND  &&  scan  <  rear )
                 if   ( target . equals ( list [ scan ]))
                    result  =  scan ;
                 else
                    scan ++ ;

         return  result ;
     }

     /**
     * Returns true if this list is empty and false otherwise. 
     *
     *  @return  true if the list is empty, false otherwise
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements currently in this list.
     *
     *  @return  the number of elements in the list
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this list. 
     * 
     *  @return  the string representation of the list
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }

     /**
     * Returns an iterator for the elements currently in this list.
     * 
     *  @return  an iterator for the elements in the list
     */
     public   Iterator < T >  iterator ()
     {
         return   new   ArrayListIterator ();
     }

     /**
     * ArrayListIterator iterator over the elements of an ArrayList.
     */  
     private   class   ArrayListIterator   implements   Iterator < T >
     {
         int  iteratorModCount ;
         int  current ;

         /**
         * Sets up this iterator using the specified modCount.
         * 
         *  @param  modCount the current modification count for the ArrayList
         */
         public   ArrayListIterator ()
         {
            iteratorModCount  =  modCount ;
            current  =   0 ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( iteratorModCount  !=  modCount )
                 throw   new   ConcurrentModificationException ();

             return   ( current  <  rear );
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return   the next element in the iteration
         *  @throws   NoSuchElementException if an element not found exception occurs
         *  @throws   ConcurrentModificationException if the collection has changed
         */
         public  T next ()   throws   ConcurrentModificationException
         {
             if   ( ! hasNext ())
                 throw   new   NoSuchElementException ();

            current ++ ;

             return  list [ current  -   1 ];
         }

         /**
         * The remove operation is not supported in this collection.
         * 
         *  @throws  UnsupportedOperationException if the remove method is called
         */
         public   void  remove ()   throws   UnsupportedOperationException
         {
             throw   new   UnsupportedOperationException ();
         }

     }    
}

Chap20/LinkedBinarySearchTree/jsjf/ArrayUnorderedList.java

Chap20/LinkedBinarySearchTree/jsjf/ArrayUnorderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayUnorderedList represents an array implementation of an unordered list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayUnorderedList < T >   extends   ArrayList < T >  
implements   UnorderedListADT < T >
{
     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayUnorderedList ()
     {
         super ();
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the initial size of the list
     */
     public   ArrayUnorderedList ( int  initialCapacity )
     {
         super ( initialCapacity );
     }

     /**
     * Adds the specified element to the front of this list.
     * 
     *  @param  element the element to be added to the front of the list
     */
     public   void  addToFront ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element to the rear of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToRear ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element after the specified target element.
     * Throws an ElementNotFoundException if the target is not found.
     *
     *  @param  element the element to be added after the target element
     *  @param  target  the target that the element is to be added after
     */
     public   void  addAfter ( T element ,  T target )
     {
         if   ( size ()   ==  list . length )
            expandCapacity ();

         int  scan  =   0 ;

         // find the insertion point
         while   ( scan  <  rear  &&   ! target . equals ( list [ scan ]))  
            scan ++ ;

         if   ( scan  ==  rear )
             throw   new   ElementNotFoundException ( "UnorderedList" );

        scan ++ ;

         // shift elements up one
         for   ( int  shift  =  rear ;  shift  >  scan ;  shift -- )
            list [ shift ]   =  list [ shift  -   1 ];

         // insert element
        list [ scan ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }
}

Chap20/LinkedBinarySearchTree/jsjf/BinarySearchTreeADT.java

Chap20/LinkedBinarySearchTree/jsjf/BinarySearchTreeADT.java

package  jsjf ;

/**
 * BinarySearchTreeADT defines the interface to a binary search tree.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   BinarySearchTreeADT < T >   extends   BinaryTreeADT < T >  
{
     /** 
     * Adds the specified element to the proper location in this tree. 
     *
     *  @param  element the element to be added to this tree
     */
     public   void  addElement ( T element );

     /** 
     * Removes and returns the specified element from this tree. 
     *
     *  @param  targetElement the element to be removed from the tree
     *  @return  the element to be removed from the tree
     */  
     public  T removeElement ( T targetElement );

     /** 
     * Removes all occurences of the specified element from this tree. 
     *
     *  @param  targetElement the element to be removed from the tree
     */
     public   void  removeAllOccurrences ( T targetElement );

     /** 
     * Removes and returns the smallest element from this tree. 
     *
     *  @return  the smallest element from the tree.
     */
     public  T removeMin ();

     /** 
     * Removes and returns the largest element from this tree. 
     *
     *  @return  the largest element from the tree
     */  
     public  T removeMax ();

     /** 
     * Returns the smallest element in this tree without removing it. 
     * 
     *  @return  the smallest element in the tree
     */  
     public  T findMin ();

     /** 
     * Returns the largest element in this tree without removing it. 
     * 
     *  @return  the largest element in the tree
     */
     public  T findMax ();
}


Chap20/LinkedBinarySearchTree/jsjf/BinaryTreeADT.java

Chap20/LinkedBinarySearchTree/jsjf/BinaryTreeADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * BinaryTreeADT defines the interface to a binary tree data structure.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   BinaryTreeADT < T >  
{
     /** 
     * Returns a reference to the root element 
     *
     *  @return  a reference to the root
     */
     public  T getRootElement ();

     /** 
     * Returns true if this binary tree is empty and false otherwise.
     *
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ();

     /** 
     * Returns the number of elements in this binary tree.
     *
     *  @return  the number of elements in the tree
     */
     public   int  size ();

     /** 
     * Returns true if the binary tree contains an element that matches
     * the specified element and false otherwise. 
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the tree contains the target element
     */
     public   boolean  contains ( T targetElement );

     /** 
     * Returns a reference to the specified element if it is found in 
     * this binary tree. Throws an exception if the specified element
     * is not found.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  a reference to the specified element
     */
     public  T find ( T targetElement );

     /**  
     * Returns the string representation of this binary tree.
     *
     *  @return  a string representation of the binary tree
     */
     public   String  toString ();

     /**  
     * Returns an iterator over the elements of this tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns an iterator that represents an inorder traversal on this binary tree.  
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorInOrder ();

     /**  
     * Returns an iterator that represents a preorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPreOrder ();

     /**  
     * Returns an iterator that represents a postorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPostOrder ();

     /**  
     * Returns an iterator that represents a levelorder traversal on the binary tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ();
}

Chap20/LinkedBinarySearchTree/jsjf/BinaryTreeNode.java

Chap20/LinkedBinarySearchTree/jsjf/BinaryTreeNode.java

package  jsjf ;

/**
 * BinaryTreeNode represents a node in a binary tree with a left and 
 * right child.
 * 
 * Solution to Programming Project 19.3 (isLeaf method)
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   BinaryTreeNode < T >
{
     protected  T element ;
     protected   BinaryTreeNode < T >  left ,  right ;

     /**
     * Creates a new tree node with the specified data.
     *
     *  @param  obj the element that will become a part of the new tree node
     */
     public   BinaryTreeNode ( T obj )  
     {
        element  =  obj ;
        left  =   null ;
        right  =   null ;
     }

     /**
     * Creates a new tree node with the specified data.
     *
     *  @param  obj the element that will become a part of the new tree node
     *  @param  left the tree that will be the left subtree of this node
     *  @param  right the tree that will be the right subtree of this node
     */
     public   BinaryTreeNode ( T obj ,   LinkedBinaryTree < T >  left ,   LinkedBinaryTree < T >  right )  
     {
        element  =  obj ;
         if   ( left  ==   null )
             this . left  =   null ;
         else
             this . left  =  left . getRootNode ();

         if   ( right  ==   null )
             this . right  =   null ;
         else
             this . right  =  right . getRootNode ();
     }

     /**
     * Returns the number of non-null children of this node.
     *
     *  @return  the integer number of non-null children of this node 
     */
     public   int  numChildren ()  
     {
         int  children  =   0 ;

         if   ( left  !=   null )
            children  =   1   +  left . numChildren ();

         if   ( right  !=   null )
            children  =  children  +   1   +  right . numChildren ();

         return  children ;
     }

     /**
     * Return true if this node is a leaf and false otherwise.
     *
     *  @return  true if this node is a leaf and false otherwise
     */
     public   boolean  isLeaf ()  
     {
         return   ( numChildren ()   ==   0 );
     }

     /**
     * Return the element at this node.
     *
     *  @return  the element stored at this node
     */
     public  T getElement ()  
     {
         return  element ;
     }

     /**
     * Return the right child of this node.
     *
     *  @return  the right child of this node
     */
     public   BinaryTreeNode < T >  getRight ()  
     {
         return  right ;
     }

     /**
     * Sets the right child of this node.
     *
     *  @param  node the right child of this node
     */
     public   void  setRight ( BinaryTreeNode < T >  node )  
     {
        right  =  node ;
     }

     /**
     * Return the left child of this node.
     *
     *  @return  the left child of the node
     */
     public   BinaryTreeNode < T >  getLeft ()  
     {
         return  left ;
     }

     /**
     * Sets the left child of this node.
     *
     *  @param  node the left child of this node
     */
     public   void  setLeft ( BinaryTreeNode < T >  node )  
     {
        left  =  node ;
     }
}

Chap20/LinkedBinarySearchTree/jsjf/exceptions/ElementNotFoundException.java

Chap20/LinkedBinarySearchTree/jsjf/exceptions/ElementNotFoundException.java

package  jsjf . exceptions ;

/**
 * ElementNotFoundException represents the situation in which a target element 
 * is not present in a collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ElementNotFoundException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     */
     public   ElementNotFoundException   ( String  collection )
     {
         super   ( "The target element is not in this "   +  collection );
     }
}

Chap20/LinkedBinarySearchTree/jsjf/exceptions/EmptyCollectionException.java

Chap20/LinkedBinarySearchTree/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " is empty." );
     }
}

Chap20/LinkedBinarySearchTree/jsjf/exceptions/NonComparableElementException.java

Chap20/LinkedBinarySearchTree/jsjf/exceptions/NonComparableElementException.java

package  jsjf . exceptions ;

/**
 * NonComparableElementException  represents the situation in which an attempt 
 * is made to add an element that is not comparable to an ordered collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   NonComparableElementException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     * 
     *  @param  collection  the exception message to deliver
     */
     public   NonComparableElementException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " requires Comparable elements." );
     }
}

Chap20/LinkedBinarySearchTree/jsjf/LinkedBinarySearchTree.java

Chap20/LinkedBinarySearchTree/jsjf/LinkedBinarySearchTree.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * LinkedBinarySearchTree implements the BinarySearchTreeADT interface 
 * with links.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinkedBinarySearchTree < T >   extends   LinkedBinaryTree < T >
implements   BinarySearchTreeADT < T >
{
     /**
     * Creates an empty binary search tree.
     */
     public   LinkedBinarySearchTree ()  
     {
         super ();
     }

     /**
     * Creates a binary search with the specified element as its root.
     *
     *  @param  element the element that will be the root of the new binary
     *        search tree
     */
     public   LinkedBinarySearchTree ( T element )  
     {
         super ( element );

         if   ( ! ( element  instanceof   Comparable ))
             throw   new   NonComparableElementException ( "LinkedBinarySearchTree" );
     }

     /**
     * Adds the specified object to the binary search tree in the
     * appropriate position according to its natural order.  Note that
     * equal elements are added to the right.
     *
     *  @param  element the element to be added to the binary search tree
     */
     public   void  addElement ( T element )  
     {
         if   ( ! ( element  instanceof   Comparable ))
             throw   new   NonComparableElementException ( "LinkedBinarySearchTree" );

         Comparable < T >  comparableElement  =   ( Comparable < T > ) element ;

         if   ( isEmpty ())
            root  =   new   BinaryTreeNode < T > ( element );
         else  
         {
             if   ( comparableElement . compareTo ( root . getElement ())   <   0 )
             {
                 if   ( root . getLeft ()   ==   null )  
                     this . getRootNode (). setLeft ( new   BinaryTreeNode < T > ( element ));
                 else
                    addElement ( element ,  root . getLeft ());
             }
             else
             {
                 if   ( root . getRight ()   ==   null )  
                     this . getRootNode (). setRight ( new   BinaryTreeNode < T > ( element ));
                 else
                    addElement ( element ,  root . getRight ());
             }
         }
        modCount ++ ;
     }

     /**
     * Adds the specified object to the binary search tree in the
     * appropriate position according to its natural order.  Note that
     * equal elements are added to the right.
     *
     *  @param  element the element to be added to the binary search tree
     */
     private   void  addElement ( T element ,   BinaryTreeNode < T >  node )  
     {
         Comparable < T >  comparableElement  =   ( Comparable < T > ) element ;

         if   ( comparableElement . compareTo ( node . getElement ())   <   0 )
         {
             if   ( node . getLeft ()   ==   null )  
                node . setLeft ( new   BinaryTreeNode < T > ( element ));
             else
                addElement ( element ,  node . getLeft ());
         }
         else
         {
             if   ( node . getRight ()   ==   null )  
                node . setRight ( new   BinaryTreeNode < T > ( element ));
             else
                addElement ( element ,  node . getRight ());
         }
     }

     /**
     * Removes the first element that matches the specified target
     * element from the binary search tree and returns a reference to
     * it.  Throws a ElementNotFoundException if the specified target
     * element is not found in the binary search tree.
     *
     *  @param  targetElement the element being sought in the binary search tree
     *  @throws  ElementNotFoundException if the target element is not found
     */
     public  T removeElement ( T targetElement )
             throws   ElementNotFoundException  
     {
        T result  =   null ;

         if   ( isEmpty ())
             throw   new   ElementNotFoundException ( "LinkedBinarySearchTree" );
         else
         {
             BinaryTreeNode < T >  parent  =   null ;
             if   ((( Comparable < T > ) targetElement ). equals ( root . element ))  
             {
                result  =   root . element ;
                 BinaryTreeNode < T >  temp  =  replacement ( root );
                 if   ( temp  ==   null )
                    root  =   null ;
                 else  
                 {
                    root . element  =  temp . element ;
                    root . setRight ( temp . right );
                    root . setLeft ( temp . left );
                 }

                modCount -- ;
             }
             else  
             {                 
                parent  =  root ;
                 if   ((( Comparable < T > ) targetElement ). compareTo ( root . element )   <   0 )
                    result  =  removeElement ( targetElement ,  root . getLeft (),  parent );
                 else
                    result  =  removeElement ( targetElement ,  root . getRight (),  parent );
             }
         }

         return  result ;
     }

     /**
     * Removes the first element that matches the specified target
     * element from the binary search tree and returns a reference to
     * it.  Throws a ElementNotFoundException if the specified target
     * element is not found in the binary search tree.
     *
     *  @param  targetElement the element being sought in the binary search tree
     *  @param  node the node from which to search
     *  @param  parent the parent of the node from which to search
     *  @throws  ElementNotFoundException if the target element is not found
     */
     private  T removeElement ( T targetElement ,   BinaryTreeNode < T >  node ,   BinaryTreeNode < T >  parent )
             throws   ElementNotFoundException  
     {
        T result  =   null ;

         if   ( node  ==   null )
             throw   new   ElementNotFoundException ( "LinkedBinarySearchTree" );
         else
         {
             if   ((( Comparable < T > ) targetElement ). equals ( node . element ))  
             {
                result  =   node . element ;
                 BinaryTreeNode < T >  temp  =  replacement ( node );
                 if   ( parent . right  ==  node )
                    parent . right  =  temp ;
                 else  
                    parent . left  =  temp ;

                modCount -- ;
             }
             else  
             {                 
                parent  =  node ;
                 if   ((( Comparable < T > ) targetElement ). compareTo ( node . element )   <   0 )
                    result  =  removeElement ( targetElement ,  node . getLeft (),  parent );
                 else
                    result  =  removeElement ( targetElement ,  node . getRight (),  parent );
             }
         }

         return  result ;
     }

     /**
     * Returns a reference to a node that will replace the one
     * specified for removal. In the case where the removed node has 
     * two children, the inorder successor is used as its replacement.
     *
     *  @param  node the node to be removed
     *  @return  a reference to the replacing node
     */
     private   BinaryTreeNode < T >  replacement ( BinaryTreeNode < T >  node )  
     {
         BinaryTreeNode < T >  result  =   null ;

         if   (( node . left  ==   null )   &&   ( node . right  ==   null ))
            result  =   null ;

         else   if   (( node . left  !=   null )   &&   ( node . right  ==   null ))
            result  =  node . left ;

         else   if   (( node . left  ==   null )   &&   ( node . right  !=   null ))
            result  =  node . right ;

         else
         {
             BinaryTreeNode < T >  current  =  node . right ;
             BinaryTreeNode < T >  parent  =  node ;

             while   ( current . left  !=   null )
             {
                parent  =  current ;
                current  =  current . left ;
             }

            current . left  =  node . left ;
             if   ( node . right  !=  current )
             {
                parent . left  =  current . right ;
                current . right  =  node . right ;
             }

            result  =  current ;
         }

         return  result ;
     }

     /**
     * Removes elements that match the specified target element from 
     * the binary search tree. Throws a ElementNotFoundException if 
     * the specified target element is not found in this tree.
     *
     *  @param  targetElement the element being sought in the binary search tree
     *  @throws  ElementNotFoundException if the target element is not found
     */
     public   void  removeAllOccurrences ( T targetElement )
             throws   ElementNotFoundException  
     {
        removeElement ( targetElement );

         try
         {
             while   ( contains (( T ) targetElement ))
                removeElement ( targetElement );
         }

         catch   ( Exception   ElementNotFoundException )
         {
         }
     }

     /**
     * Removes the node with the least value from the binary search
     * tree and returns a reference to its element. Throws an
     * EmptyCollectionException if this tree is empty. 
     *
     *  @return  a reference to the node with the least value
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T removeMin ()   throws   EmptyCollectionException  
     {
        T result  =   null ;

         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "LinkedBinarySearchTree" );
         else  
         {
             if   ( root . left  ==   null )  
             {
                result  =  root . element ;
                root  =  root . right ;
             }
             else  
             {
                 BinaryTreeNode < T >  parent  =  root ;
                 BinaryTreeNode < T >  current  =  root . left ;
                 while   ( current . left  !=   null )  
                 {
                    parent  =  current ;
                    current  =  current . left ;
                 }
                result  =   current . element ;
                parent . left  =  current . right ;
             }

            modCount -- ;
         }

         return  result ;
     }

     /**
     * Removes the node with the highest value from the binary
     * search tree and returns a reference to its element. Throws an
     * EmptyCollectionException if this tree is empty. 
     *
     *  @return  a reference to the node with the highest value
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T removeMax ()   throws   EmptyCollectionException  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the element with the least value in the binary search
     * tree. It does not remove the node from the binary search tree. 
     * Throws an EmptyCollectionException if this tree is empty.
     *
     *  @return  the element with the least value
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T findMin ()   throws   EmptyCollectionException  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the element with the highest value in the binary
     * search tree. It does not remove the node from the binary
     * search tree. Throws an EmptyCollectionException if this 
     * tree is empty.
     *
     *  @return  the element with the highest value
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T findMax ()   throws   EmptyCollectionException  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the left subtree of the root of this tree.
     *
     *  @return  a link to the left subtree of the tree
     */
     public   LinkedBinarySearchTree < T >  getLeft ()
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the right subtree of the root of this tree.
     *
     *  @return  a link to the right subtree of the tree
     */
     public   LinkedBinarySearchTree < T >  getRight ()
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }
}

Chap20/LinkedBinarySearchTree/jsjf/LinkedBinaryTree.java

Chap20/LinkedBinarySearchTree/jsjf/LinkedBinaryTree.java

package  jsjf ;

import  java . util . * ;
import  jsjf . exceptions . * ;

/**
 * LinkedBinaryTree implements the BinaryTreeADT interface.
 * 
 * Solution to Programming Projects 19.1, 19.2, 19.5, 19.7
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinkedBinaryTree < T >   implements   BinaryTreeADT < T > ,   Iterable < T >
{
     protected   BinaryTreeNode < T >  root ;  
     protected   int  modCount ;

     /**
     * Creates an empty binary tree.
     */
     public   LinkedBinaryTree ()  
     {
        root  =   null ;
     }

     /**
     * Creates a binary tree with the specified element as its root.
     *
     *  @param  element the element that will become the root of the binary tree
     */
     public   LinkedBinaryTree ( T element )  
     {
        root  =   new   BinaryTreeNode < T > ( element );
     }

     /**
     * Creates a binary tree with the specified element as its root and the 
     * given trees as its left child and right child
     *
     *  @param  element the element that will become the root of the binary tree
     *  @param  left the left subtree of this tree
     *  @param  right the right subtree of this tree
     */
     public   LinkedBinaryTree ( T element ,   LinkedBinaryTree < T >  left ,  
             LinkedBinaryTree < T >  right )  
     {
        root  =   new   BinaryTreeNode < T > ( element );
        root . setLeft ( left . root );
        root . setRight ( right . root );
     }

     /**
     * Returns a reference to the element at the root
     *
     *  @return  a reference to the specified target
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T getRootElement ()   throws   EmptyCollectionException
     {
         if   ( root  ==   null )
             throw   new   EmptyCollectionException ( "LinkedBinaryTree" );
        
         return   ( root . getElement ());
     }

     /**
     * Returns a reference to the node at the root
     *
     *  @return  a reference to the specified node
     *  @throws  EmptyCollectionException if the tree is empty
     */
     protected   BinaryTreeNode < T >  getRootNode ()   throws   EmptyCollectionException
     {
         if   ( root  ==   null )
             throw   new   EmptyCollectionException ( "LinkedBinaryTree" );
        
         return   ( root );
     }

     /**
     * Returns the left subtree of the root of this tree.
     *
     *  @return  a link to the left subtree of the tree
     */
     public   LinkedBinaryTree < T >  getLeft ()
     {
         if   ( root  ==   null )
             throw   new   EmptyCollectionException ( "Get left operation "
                     +   "failed. The tree is empty." );

         LinkedBinaryTree < T >  result  =   new   LinkedBinaryTree < T > ();
        result . root  =  root . getLeft ();
        
         return  result ;
     }

     /**
     * Returns the right subtree of the root of this tree.
     *
     *  @return  a link to the right subtree of the tree
     */
     public   LinkedBinaryTree < T >  getRight ()
     {
         if   ( root  ==   null )
             throw   new   EmptyCollectionException ( "Get right operation "
                     +   "failed. The tree is empty." );

         LinkedBinaryTree < T >  result  =   new   LinkedBinaryTree < T > ();
        result . root  =  root . getRight ();

         return  result ;
     }

     /**
     * Returns true if this binary tree is empty and false otherwise.
     *
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ()  
     {
         return   ( root  ==   null );
     }

     /**
     * Returns the integer size of this tree.
     *
     *  @return  the integer size of the tree
     */
     public   int  size ()  
     {
         return  root . numChildren ()   +   1 ;
     }

     /**
     * Returns the height of this tree.
     *
     *  @return  the height of the tree
     */
     public   int  getHeight ()
     {
         return  height ( root )   -   1 ;
     }

     /**
     * Returns the height of the specified node.
     *
     *  @param  node the node from which to calculate the height
     *  @return  the height of the tree
     */
     private   int  height ( BinaryTreeNode < T >  node )  
     {
         int  result  =   0 ;
         if   ( node  !=   null )
            result  =   Math . max ( height ( node . getLeft ()),  height ( node . getRight ()))   +   1 ;

         return  result ;
     }

     /**
     * Returns true if this tree contains an element that matches the
     * specified target element and false otherwise.
     *
     *  @param  targetElement the element being sought in this tree
     *  @return  true if the element in is this tree, false otherwise
     */
     public   boolean  contains ( T targetElement )  
     {
        T temp ;
         boolean  found  =   false ;
        
         try  
         {
            temp  =  find ( targetElement );
            found  =   true ;
         }
         catch   ( Exception   ElementNotFoundException )  
         {
            found  =   false ;
         }
        
         return  found ;
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this binary tree.  Throws a ElementNotFoundException if
     * the specified target element is not found in the binary tree.
     *
     *  @param  targetElement the element being sought in this tree
     *  @return  a reference to the specified target
     *  @throws  ElementNotFoundException if the element is not in the tree
     */
     public  T find ( T targetElement )   throws   ElementNotFoundException
     {
         BinaryTreeNode < T >  current  =  findNode ( targetElement ,  root );

         if   ( current  ==   null )
             throw   new   ElementNotFoundException ( "LinkedBinaryTree" );

         return   ( current . getElement ());
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this binary tree.
     *
     *  @param  targetElement the element being sought in this tree
     *  @param  next the element to begin searching from
     */
     private   BinaryTreeNode < T >  findNode ( T targetElement ,  
             BinaryTreeNode < T >  next )
     {
         if   ( next  ==   null )
             return   null ;

         if   ( next . getElement (). equals ( targetElement ))
             return  next ;

         BinaryTreeNode < T >  temp  =  findNode ( targetElement ,  next . getLeft ());

         if   ( temp  ==   null )
            temp  =  findNode ( targetElement ,  next . getRight ());

         return  temp ;
     }

     /**
     * Returns a string representation of this binary tree showing
     * the nodes in an inorder fashion.
     *
     *  @return  a string representation of this binary tree
     */
     public   String  toString ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        inOrder ( root ,  tempList );
        
         return  tempList . toString ();
     }

     /**
     * Returns an iterator over the elements in this tree using the 
     * iteratorInOrder method
     *
     *  @return  an in order iterator over this binary tree
     */
     public   Iterator < T >  iterator ()
     {
         return  iteratorInOrder ();
     }

     /**
     * Performs an inorder traversal on this binary tree by calling an
     * overloaded, recursive inorder method that starts with
     * the root.
     *
     *  @return  an in order iterator over this binary tree
     */
     public   Iterator < T >  iteratorInOrder ()
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        inOrder ( root ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive inorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  inOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  !=   null )
         {
            inOrder ( node . getLeft (),  tempList );
            tempList . addToRear ( node . getElement ());
            inOrder ( node . getRight (),  tempList );
         }
     }

     /**
     * Performs an preorder traversal on this binary tree by calling 
     * an overloaded, recursive preorder method that starts with
     * the root.
     *
     *  @return  a pre order iterator over this tree
     */
     public   Iterator < T >  iteratorPreOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        preOrder ( root ,  tempList );
        
         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive preorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  preOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  !=   null )
         {
            tempList . addToRear ( node . getElement ());
            preOrder ( node . getLeft (),  tempList );
            preOrder ( node . getRight (),  tempList );
         }
     }

     /**
     * Performs an postorder traversal on this binary tree by calling
     * an overloaded, recursive postorder method that starts
     * with the root.
     *
     *  @return  a post order iterator over this tree
     */
     public   Iterator < T >  iteratorPostOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        postOrder ( root ,  tempList );
        
         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive postorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  postOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  !=   null )
         {
            postOrder ( node . getLeft (),  tempList );
            postOrder ( node . getRight (),  tempList );
            tempList . addToRear ( node . getElement ());
         }
     }

     /**
     * Performs a levelorder traversal on this binary tree, using a
     * templist.
     *
     *  @return  a levelorder iterator over this binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ()  
     {
         ArrayUnorderedList < BinaryTreeNode < T >>  nodes  =  
                 new   ArrayUnorderedList < BinaryTreeNode < T >> ();
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
         BinaryTreeNode < T >  current ;

        nodes . addToRear ( root );

         while   ( ! nodes . isEmpty ())  
         {
            current  =  nodes . removeFirst ();

             if   ( current  !=   null )
             {
                tempList . addToRear ( current . getElement ());
                 if   ( current . getLeft ()   !=   null )
                    nodes . addToRear ( current . getLeft ());
                 if   ( current . getRight ()   !=   null )
                    nodes . addToRear ( current . getRight ());
             }
             else
                tempList . addToRear ( null );
         }

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Inner class to represent an iterator over the elements of this tree
     */
     private   class   TreeIterator   implements   Iterator < T >
     {
         private   int  expectedModCount ;
         private   Iterator < T >  iter ;

         /**
         * Sets up this iterator using the specified iterator.
         *
         *  @param  iter the list iterator created by a tree traversal
         */
         public   TreeIterator ( Iterator < T >  iter )
         {
             this . iter  =  iter ;
            expectedModCount  =  modCount ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( ! ( modCount  ==  expectedModCount ))
                 throw   new   ConcurrentModificationException ();

             return   ( iter . hasNext ());
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return  the next element in the iteration
         *  @throws  NoSuchElementException if the iterator is empty
         */
         public  T next ()   throws   NoSuchElementException
         {
             if   ( hasNext ())
                 return   ( iter . next ());
             else  
                 throw   new   NoSuchElementException ();
         }

         /**
         * The remove operation is not supported.
         * 
         *  @throws  UnsupportedOperationException if the remove operation is called
         */
         public   void  remove ()
         {
             throw   new   UnsupportedOperationException ();
         }
     }
}

Chap20/LinkedBinarySearchTree/jsjf/ListADT.java

Chap20/LinkedBinarySearchTree/jsjf/ListADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * ListADT defines the interface to a general list collection. Specific
 * types of lists will extend this interface to complete the
 * set of necessary operations.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   ListADT < T >   extends   Iterable < T >
{
     /**  
     * Removes and returns the first element from this list. 
     * 
     *  @return  the first element from this list
     */
     public  T removeFirst ();

     /**  
     * Removes and returns the last element from this list. 
     *
     *  @return  the last element from this list
     */
     public  T removeLast ();

     /**  
     * Removes and returns the specified element from this list. 
     *
     *  @param  element the element to be removed from the list
     */
     public  T remove ( T element );

     /**  
     * Returns a reference to the first element in this list. 
     *
     *  @return  a reference to the first element in this list
     */
     public  T first ();

     /**  
     * Returns a reference to the last element in this list. 
     *
     *  @return  a reference to the last element in this list
     */
     public  T last ();

     /**  
     * Returns true if this list contains the specified target element. 
     *
     *  @param  target the target that is being sought in the list
     *  @return  true if the list contains this element
     */
     public   boolean  contains ( T target );

     /**  
     * Returns true if this list contains no elements. 
     *
     *  @return  true if this list contains no elements
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this list. 
     *
     *  @return  the integer representation of number of elements in this list
     */
     public   int  size ();

     /**  
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements in this list
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns a string representation of this list. 
     *
     *  @return  a string representation of this list
     */
     public   String  toString ();
}

Chap20/LinkedBinarySearchTree/jsjf/UnorderedListADT.java

Chap20/LinkedBinarySearchTree/jsjf/UnorderedListADT.java

package  jsjf ;

/**
 * UnorderedListADT defines the interface to an unordered list collection. 
 * Elements are stored in any order the user desires.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   UnorderedListADT < T >   extends   ListADT < T >
{
     /**  
     * Adds the specified element to the front of this list. 
     *
     *  @param  element the element to be added to the front of this list    
     */
     public   void  addToFront ( T element );   

     /**  
     * Adds the specified element to the rear of this list. 
     *
     *  @param  element the element to be added to the rear of this list    
     */
     public   void  addToRear ( T element );  

     /**  
     * Adds the specified element after the specified target. 
     *
     *  @param  element the element to be added after the target
     *  @param  target  the target is the item that the element will be added
     *                after    
     */
     public   void  addAfter ( T element ,  T target );
}

Chap21/ArrayHeap/jsjf/ArrayBinaryTree.java

Chap21/ArrayHeap/jsjf/ArrayBinaryTree.java

package  jsjf ;

import  java . util . * ;
import  jsjf . exceptions . * ;

/**
 * ArrayBinaryTree implements the BinaryTreeADT interface using an array.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayBinaryTree < T >   implements   BinaryTreeADT < T > ,   Iterable < T >
{
     private   static   final   int  DEFAULT_CAPACITY  =   50 ;

     protected   int  count ;
     protected  T []  tree ;  
     protected   int  modCount ;

     /**
     * Creates an empty binary tree.
     */
     public   ArrayBinaryTree ()  
     {
        count  =   0 ;
        tree  =   ( T [])   new   Object [ DEFAULT_CAPACITY ];
     }

     /**
     * Creates a binary tree with the specified element as its root.
     *
     *  @param  element the element which will become the root of the new tree
     */
     public   ArrayBinaryTree ( T element )  
     {
        count  =   1 ;
        tree  =   ( T [])   new   Object [ DEFAULT_CAPACITY ];
        tree [ 0 ]   =  element ;
     }

     /**
     * Private method to expand capacity if full.
     */     
     protected   void  expandCapacity ()
     {
        tree  =   Arrays . copyOf ( tree ,  tree . length  *   2 );    
     }

     /**
     * Returns the root element of the tree.
     *
     *  @return  element stored at the root
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T getRootElement ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "ArrayBinaryTree" );

         return  tree [ 0 ];
     }

     /**
     * Returns true if this binary tree is empty and false otherwise.
     * 
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ()  
     {
         return   ( count  ==   0 );
     }

     /**
     * Returns the integer size of this binary tree.
     *
     *  @return  the integer size of this binary tree
     */
     public   int  size ()  
     {
         return  count ;
     }

     /**
     * Returns true if this tree contains an element that matches the
     * specified target element and false otherwise.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the element is in this tree
     */
     public   boolean  contains ( T targetElement )  
     {
        T temp ;
         boolean  found  =   false ;

         try  
         {
            temp  =  find ( targetElement );
            found  =   true ;
         }
         catch   ( Exception   ElementNotFoundException )  
         {
            found  =   false ;
         }

         return  found ;
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this binary tree.  Throws a ElementNotFoundException if
     * the specified target element is not found in the binary tree.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the element is in the tree
     *  @throws  ElementNotFoundException if the element is not in the tree
     */
     public  T find ( T targetElement )   throws   ElementNotFoundException  
     {
        T temp  =   null ;
         boolean  found  =   false ;

         for   ( int  i  =   0 ;  i  <  tree . length  &&   ! found ;  i ++ )
             if   ( tree [ i ]   !=   null )
                 if   ( targetElement . equals ( tree [ i ]))
                 {
                    found  =   true ;
                    temp  =  tree [ i ];
                 }

         if   ( ! found )
             throw   new   ElementNotFoundException ( "ArrayBinaryTree" );

         return  temp ;
     }


     /**
     * Returns a string representation of this binary tree showing
     * the nodes in an inorder fashion.
     *
     *  @return  a string representation of the binary tree
     */
     public   String  toString ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        inOrder ( 0 ,  tempList );

         return  tempList . toString ();
     }

     /**
     * Returns an iterator over the elements of this binary tree using
     * the iteratorInOrder method
     *
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iterator ()  
     {
         return   this . iteratorInOrder ();
     }

     /**
     * Performs an inorder traversal on this binary tree by calling an
     * overloaded, recursive inorder method that starts with
     * the root.
     *
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iteratorInOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        inOrder ( 0 ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive inorder traversal.
     *
     *  @param  node the index of the node used in the traversal
     *  @param  tempList the temporary list used in the traversal
     */
     protected   void  inOrder ( int  node ,   ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  <  tree . length )
             if   ( tree [ node ]   !=   null )
             {
                inOrder ( node  *   2   +   1 ,  tempList );
                tempList . addToRear ( tree [ node ]);
                inOrder (( node  +   1 )   *   2 ,  tempList );
             }
     }

     /**
     * Performs an preorder traversal on this binary tree by calling an
     * overloaded, recursive preorder method that starts with
     * the root.
     * 
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iteratorPreOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        preOrder ( 0 ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive preorder traversal.
     *
     *  @param  node the index of the node used in the traversal
     *  @param  tempList the temporary list used in the traversal
     */
     protected   void  preOrder ( int  node ,   ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  <  tree . length )
             if   ( tree [ node ]   !=   null )  
             {  
                tempList . addToRear ( tree [ node ]);
                preOrder ( node  *   2   +   1 ,  tempList );
                preOrder (( node  +   1 )   *   2 ,  tempList );
             }
     }

     /**
     * Performs an postorder traversal on the binary tree by calling
     * an overloaded, recursive postorder method that starts
     * with the root.
     * 
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iteratorPostOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        postOrder ( 0 ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive postorder traversal.
     * 
     *  @param  node the index of the node used in the traversal
     *  @param  tempList the temporary list used in the traversal
     */
     protected   void  postOrder ( int  node ,   ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  <  tree . length )
             if   ( tree [ node ]   !=   null )  
             {
                postOrder ( node  *   2   +   1 ,  tempList );  
                postOrder (( node  +   1 )   *   2 ,  tempList );
                tempList . addToRear ( tree [ node ]);   
             }
     }

     /**
     * Performs a levelorder traversal on this binary tree, using a
     * tempList.
     *
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
         int  ct  =   0 ;   // current number of elements added to list
         int  i  =   0 ;   // current position in array

         while   ( ct  <  count )
         {
             if   ( tree [ i ]   !=   null )
             {
                tempList . addToRear ( tree [ i ]);
                ct ++ ;
             }
            i ++ ;
         }

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Inner class to represent an iterator over the elements of this tree
     */
     private   class   TreeIterator   implements   Iterator < T >
     {
         private   int  expectedModCount ;
         private   Iterator < T >  iter ;

         /**
         * Sets up this iterator using the specified iterator.
         *
         *  @param  iter the list iterator created by a tree traversal
         */
         public   TreeIterator ( Iterator < T >  iter )
         {
             this . iter  =  iter ;
            expectedModCount  =  modCount ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( ! ( modCount  ==  expectedModCount ))
                 throw   new   ConcurrentModificationException ();

             return   ( iter . hasNext ());
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return  the next element in the iteration
         *  @throws  NoSuchElementException if the iterator is empty
         */
         public  T next ()   throws   NoSuchElementException
         {
             if   ( hasNext ())
                 return   ( iter . next ());
             else  
                 throw   new   NoSuchElementException ();
         }

         /**
         * The remove operation is not supported.
         * 
         *  @throws  UnsupportedOperationException if the remove operation is called
         */
         public   void  remove ()
         {
             throw   new   UnsupportedOperationException ();
         }
     }
}

Chap21/ArrayHeap/jsjf/ArrayHeap.java

Chap21/ArrayHeap/jsjf/ArrayHeap.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayHeap provides an array implementation of a minheap.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayHeap < T >   extends   ArrayBinaryTree < T >   implements   HeapADT < T >  
{
     /**
     * Creates an empty heap.
     */
     public   ArrayHeap ()  
     {
         super ();
     }

     /**
     * Adds the specified element to this heap in the appropriate
     * position according to its key value.  
     *
     *  @param  obj the element to be added to the heap
     */
     public   void  addElement ( T obj )  
     {
         if   ( count  ==  tree . length )
            expandCapacity ();

        tree [ count ]   =  obj ;
        count ++ ;
        modCount ++ ;

         if   ( count  >   1 )
            heapifyAdd ();
     }

     /**
     * Reorders this heap to maintain the ordering property after
     * adding a node.
     */
     private   void  heapifyAdd ()
     {
        T temp ;
         int  next  =  count  -   1 ;

        temp  =  tree [ next ];

         while   (( next  !=   0 )   &&  
                 ((( Comparable < T > ) temp ). compareTo ( tree [( next  -   1 )   /   2 ])   <   0 ))
         {

            tree [ next ]   =  tree [( next  -   1 )   /   2 ];
            next  =   ( next  -   1 )   /   2 ;
         }

        tree [ next ]   =  temp ;
     }

     /**
     * Remove the element with the lowest value in this heap and
     * returns a reference to it. Throws an EmptyCollectionException if
     * the heap is empty.
     *
     *  @return  a reference to the element with the lowest value in this heap
     *  @throws  EmptyCollectionException if the heap is empty
     */
     public  T removeMin ()   throws   EmptyCollectionException  
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "ArrayHeap" );

        T minElement  =  tree [ 0 ];
        tree [ 0 ]   =  tree [ count  -   1 ];
        heapifyRemove ();
        count -- ;
        modCount -- ;

         return  minElement ;
     }

     /**
     * Reorders this heap to maintain the ordering property
     * after the minimum element has been removed.
     */
     private   void  heapifyRemove ()
     {
        T temp ;
         int  node  =   0 ;
         int  left  =   1 ;
         int  right  =   2 ;
         int  next ;

         if   (( tree [ left ]   ==   null )   &&   ( tree [ right ]   ==   null ))
            next  =  count ;
         else   if   ( tree [ right ]   ==   null )
            next  =  left ;
         else   if   ((( Comparable < T > ) tree [ left ]). compareTo ( tree [ right ])   <   0 )
            next  =  left ;
         else
            next  =  right ;
        temp  =  tree [ node ];

         while   (( next  <  count )   &&  
                 ((( Comparable < T > ) tree [ next ]). compareTo ( temp )   <   0 ))
         {
            tree [ node ]   =  tree [ next ];
            node  =  next ;
            left  =   2   *  node  +   1 ;
            right  =   2   *   ( node  +   1 );
             if   (( tree [ left ]   ==   null )   &&   ( tree [ right ]   ==   null ))
                next  =  count ;
             else   if   ( tree [ right ]   ==   null )
                next  =  left ;
             else   if   ((( Comparable < T > ) tree [ left ]). compareTo ( tree [ right ])   <   0 )
                next  =  left ;
             else
                next  =  right ;
         }
        tree [ node ]   =  temp ;
     }

     /**
     * Returns the element with the lowest value in this heap.
     * Throws an EmptyCollectionException if the heap is empty.
     *
     *  @return  the element with the lowest value in this heap
     *  @throws  EmptyCollectionException if the heap is empty
     */
     public  T findMin ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "ArrayHeap" );

         return  tree [ 0 ];
     }
}


Chap21/ArrayHeap/jsjf/ArrayList.java

Chap21/ArrayHeap/jsjf/ArrayList.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . * ;

/**
 * ArrayList represents an array implementation of a list. The front of
 * the list is kept at array index 0. This class will be extended
 * to create a specific kind of list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   abstract   class   ArrayList < T >   implements   ListADT < T > ,   Iterable < T >
{
     private   final   static   int  DEFAULT_CAPACITY  =   100 ;
     private   final   static   int  NOT_FOUND  =   - 1 ;

     protected   int  rear ;
     protected  T []  list ;  
     protected   int  modCount ;

     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayList ()
     {
         this ( DEFAULT_CAPACITY );
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the integer value of the size of the array list
     */
     public   ArrayList ( int  initialCapacity )
     {
        rear  =   0 ;
        list  =   ( T [])( new   Object [ initialCapacity ]);
        modCount  =   0 ;
     }

     /**
     * Creates a new array to store the contents of this list with
     * twice the capacity of the old one. Called by descendant classes
     * that add elements to the list.
     */
     protected   void  expandCapacity ()
     {
         // To be completed as a Programming Project
     }

     /**
     * Removes and returns the last element in this list.
     *
     *  @return  the last element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeLast ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the first element in this list.
     *
     *  @return  the first element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeFirst ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the specified element.
     *
     *  @param   element the element to be removed and returned from the list
     *  @return  the removed elememt
     *  @throws  ElementNotFoundException if the element is not in the list
     */
     public  T remove ( T element )
     {
        T result ;
         int  index  =  find ( element );

         if   ( index  ==  NOT_FOUND )
             throw   new   ElementNotFoundException ( "ArrayList" );

        result  =  list [ index ];
        rear -- ;

         // shift the appropriate elements 
         for   ( int  scan  =  index ;  scan  <  rear ;  scan ++ )
            list [ scan ]   =  list [ scan + 1 ];

        list [ rear ]   =   null ;
        modCount ++ ;

         return  result ;
     }

     /**
     * Returns a reference to the element at the front of this list.
     * The element is not removed from the list.  Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the first element in the list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the element at the rear of this list.
     * The element is not removed from the list. Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the last element of this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T last ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this list contains the specified element.
     *
     *  @param  target the target element
     *  @return  true if the target is in the list, false otherwise 
     */
     public   boolean  contains ( T target )
     {
         return   ( find ( target )   !=  NOT_FOUND );
     }

     /**
     * Returns the array index of the specified element, or the
     * constant NOT_FOUND if it is not found.
     *
     *  @param  target the target element
     *  @return  the index of the target element, or the 
     *         NOT_FOUND constant
     */
     private   int  find ( T target )
     {
         int  scan  =   0 ;  
         int  result  =  NOT_FOUND ;

         if   ( ! isEmpty ())
             while   ( result  ==  NOT_FOUND  &&  scan  <  rear )
                 if   ( target . equals ( list [ scan ]))
                    result  =  scan ;
                 else
                    scan ++ ;

         return  result ;
     }

     /**
     * Returns true if this list is empty and false otherwise. 
     *
     *  @return  true if the list is empty, false otherwise
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements currently in this list.
     *
     *  @return  the number of elements in the list
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this list. 
     * 
     *  @return  the string representation of the list
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }

     /**
     * Returns an iterator for the elements currently in this list.
     * 
     *  @return  an iterator for the elements in the list
     */
     public   Iterator < T >  iterator ()
     {
         return   new   ArrayListIterator ();
     }

     /**
     * ArrayListIterator iterator over the elements of an ArrayList.
     */  
     private   class   ArrayListIterator   implements   Iterator < T >
     {
         int  iteratorModCount ;
         int  current ;

         /**
         * Sets up this iterator using the specified modCount.
         * 
         *  @param  modCount the current modification count for the ArrayList
         */
         public   ArrayListIterator ()
         {
            iteratorModCount  =  modCount ;
            current  =   0 ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( iteratorModCount  !=  modCount )
                 throw   new   ConcurrentModificationException ();

             return   ( current  <  rear );
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return   the next element in the iteration
         *  @throws   NoSuchElementException if an element not found exception occurs
         *  @throws   ConcurrentModificationException if the collection has changed
         */
         public  T next ()   throws   ConcurrentModificationException
         {
             if   ( ! hasNext ())
                 throw   new   NoSuchElementException ();

            current ++ ;

             return  list [ current  -   1 ];
         }

         /**
         * The remove operation is not supported in this collection.
         * 
         *  @throws  UnsupportedOperationException if the remove method is called
         */
         public   void  remove ()   throws   UnsupportedOperationException
         {
             throw   new   UnsupportedOperationException ();
         }

     }    
}

Chap21/ArrayHeap/jsjf/ArrayUnorderedList.java

Chap21/ArrayHeap/jsjf/ArrayUnorderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayUnorderedList represents an array implementation of an unordered list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayUnorderedList < T >   extends   ArrayList < T >  
implements   UnorderedListADT < T >
{
     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayUnorderedList ()
     {
         super ();
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the initial size of the list
     */
     public   ArrayUnorderedList ( int  initialCapacity )
     {
         super ( initialCapacity );
     }

     /**
     * Adds the specified element to the front of this list.
     * 
     *  @param  element the element to be added to the front of the list
     */
     public   void  addToFront ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element to the rear of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToRear ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element after the specified target element.
     * Throws an ElementNotFoundException if the target is not found.
     *
     *  @param  element the element to be added after the target element
     *  @param  target  the target that the element is to be added after
     */
     public   void  addAfter ( T element ,  T target )
     {
         if   ( size ()   ==  list . length )
            expandCapacity ();

         int  scan  =   0 ;

         // find the insertion point
         while   ( scan  <  rear  &&   ! target . equals ( list [ scan ]))  
            scan ++ ;

         if   ( scan  ==  rear )
             throw   new   ElementNotFoundException ( "UnorderedList" );

        scan ++ ;

         // shift elements up one
         for   ( int  shift  =  rear ;  shift  >  scan ;  shift -- )
            list [ shift ]   =  list [ shift  -   1 ];

         // insert element
        list [ scan ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }
}

Chap21/ArrayHeap/jsjf/BinaryTreeADT.java

Chap21/ArrayHeap/jsjf/BinaryTreeADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * BinaryTreeADT defines the interface to a binary tree data structure.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   BinaryTreeADT < T >  
{
     /** 
     * Returns a reference to the root element 
     *
     *  @return  a reference to the root
     */
     public  T getRootElement ();

     /** 
     * Returns true if this binary tree is empty and false otherwise.
     *
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ();

     /** 
     * Returns the number of elements in this binary tree.
     *
     *  @return  the number of elements in the tree
     */
     public   int  size ();

     /** 
     * Returns true if the binary tree contains an element that matches
     * the specified element and false otherwise. 
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the tree contains the target element
     */
     public   boolean  contains ( T targetElement );

     /** 
     * Returns a reference to the specified element if it is found in 
     * this binary tree. Throws an exception if the specified element
     * is not found.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  a reference to the specified element
     */
     public  T find ( T targetElement );

     /**  
     * Returns the string representation of this binary tree.
     *
     *  @return  a string representation of the binary tree
     */
     public   String  toString ();

     /**  
     * Returns an iterator over the elements of this tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns an iterator that represents an inorder traversal on this binary tree.  
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorInOrder ();

     /**  
     * Returns an iterator that represents a preorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPreOrder ();

     /**  
     * Returns an iterator that represents a postorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPostOrder ();

     /**  
     * Returns an iterator that represents a levelorder traversal on the binary tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ();
}

Chap21/ArrayHeap/jsjf/exceptions/ElementNotFoundException.java

Chap21/ArrayHeap/jsjf/exceptions/ElementNotFoundException.java

package  jsjf . exceptions ;

/**
 * ElementNotFoundException represents the situation in which a target element 
 * is not present in a collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ElementNotFoundException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     */
     public   ElementNotFoundException   ( String  collection )
     {
         super   ( "The target element is not in this "   +  collection );
     }
}

Chap21/ArrayHeap/jsjf/exceptions/EmptyCollectionException.java

Chap21/ArrayHeap/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " is empty." );
     }
}

Chap21/ArrayHeap/jsjf/exceptions/NonComparableElementException.java

Chap21/ArrayHeap/jsjf/exceptions/NonComparableElementException.java

package  jsjf . exceptions ;

/**
 * NonComparableElementException  represents the situation in which an attempt 
 * is made to add an element that is not comparable to an ordered collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   NonComparableElementException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     * 
     *  @param  collection  the exception message to deliver
     */
     public   NonComparableElementException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " requires Comparable elements." );
     }
}

Chap21/ArrayHeap/jsjf/HeapADT.java

Chap21/ArrayHeap/jsjf/HeapADT.java

package  jsjf ;

/**
 * HeapADT defines the interface to a Heap.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   HeapADT < T >   extends   BinaryTreeADT < T >  
{
     /** 
     * Adds the specified object to this heap. 
     *
     *  @param  obj the element to be added to the heap
     */    
     public   void  addElement ( T obj );

     /** 
     * Removes element with the lowest value from this heap. 
     *
     *  @return  the element with the lowest value from the heap
     */
     public  T removeMin ();

     /** 
     * Returns a reference to the element with the lowest value in 
     * this heap. 
     *
     *  @return  a reference to the element with the lowest value in the heap
     */
     public  T findMin ();
}


Chap21/ArrayHeap/jsjf/ListADT.java

Chap21/ArrayHeap/jsjf/ListADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * ListADT defines the interface to a general list collection. Specific
 * types of lists will extend this interface to complete the
 * set of necessary operations.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   ListADT < T >   extends   Iterable < T >
{
     /**  
     * Removes and returns the first element from this list. 
     * 
     *  @return  the first element from this list
     */
     public  T removeFirst ();

     /**  
     * Removes and returns the last element from this list. 
     *
     *  @return  the last element from this list
     */
     public  T removeLast ();

     /**  
     * Removes and returns the specified element from this list. 
     *
     *  @param  element the element to be removed from the list
     */
     public  T remove ( T element );

     /**  
     * Returns a reference to the first element in this list. 
     *
     *  @return  a reference to the first element in this list
     */
     public  T first ();

     /**  
     * Returns a reference to the last element in this list. 
     *
     *  @return  a reference to the last element in this list
     */
     public  T last ();

     /**  
     * Returns true if this list contains the specified target element. 
     *
     *  @param  target the target that is being sought in the list
     *  @return  true if the list contains this element
     */
     public   boolean  contains ( T target );

     /**  
     * Returns true if this list contains no elements. 
     *
     *  @return  true if this list contains no elements
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this list. 
     *
     *  @return  the integer representation of number of elements in this list
     */
     public   int  size ();

     /**  
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements in this list
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns a string representation of this list. 
     *
     *  @return  a string representation of this list
     */
     public   String  toString ();
}

Chap21/ArrayHeap/jsjf/UnorderedListADT.java

Chap21/ArrayHeap/jsjf/UnorderedListADT.java

package  jsjf ;

/**
 * UnorderedListADT defines the interface to an unordered list collection. 
 * Elements are stored in any order the user desires.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   UnorderedListADT < T >   extends   ListADT < T >
{
     /**  
     * Adds the specified element to the front of this list. 
     *
     *  @param  element the element to be added to the front of this list    
     */
     public   void  addToFront ( T element );   

     /**  
     * Adds the specified element to the rear of this list. 
     *
     *  @param  element the element to be added to the rear of this list    
     */
     public   void  addToRear ( T element );  

     /**  
     * Adds the specified element after the specified target. 
     *
     *  @param  element the element to be added after the target
     *  @param  target  the target is the item that the element will be added
     *                after    
     */
     public   void  addAfter ( T element ,  T target );
}

Chap21/HeapSort/Contact.java

Chap21/HeapSort/Contact.java

/**
 * Contact represents a phone contact.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   Contact   implements   Comparable < Contact >
{
     private   String  firstName ,  lastName ,  phone ;

     /**
     * Sets up this contact with the specified information.
     *
     *  @param  first     a string representation of a first name
     *  @param  last      a string representation of a last name
     *  @param  telephone a string representation of a phone number
     */
     public   Contact ( String  first ,   String  last ,   String  telephone )
     {
        firstName  =  first ;
        lastName  =  last ;
        phone  =  telephone ;
     }

     /**
     * Returns a description of this contact as a string.
     *
     *  @return  a string representation of this contact
     */
     public   String  toString ()
     {
         return  lastName  +   ", "   +  firstName  +   "\t"   +  phone ;
     }

     /**
     * Uses both last and first names to determine lexical ordering.
     *
     *  @param  other the contact to be compared to this contact
     *  @return       the integer result of the comparison
     */
     public   int  compareTo ( Contact  other )
     {
         int  result ;

         if   ( lastName . equals ( other . lastName ))
            result  =  firstName . compareTo ( other . firstName );
         else
            result  =  lastName . compareTo ( other . lastName );

         return  result ;
     }
}

Chap21/HeapSort/HeapSort.java

Chap21/HeapSort/HeapSort.java

import  jsjf . ArrayHeap ;

/**
 * HeapSort sorts a given array of Comparable objects using a heap.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   HeapSort < T >
{
     /**
     * Sorts the specified array using a Heap
     *
     *  @param  data the data to be added to the heapsort
     */
     public   void  heapSort ( T []  data )  
     {
         ArrayHeap < T >  heap  =   new   ArrayHeap < T > ();

         // copy the array into a heap 
         for   ( int  i  =   0 ;  i  <  data . length ;  i ++ )
            heap . addElement ( data [ i ]);

         // place the sorted elements back into the array 
         int  count  =   0 ;
         while   ( ! ( heap . isEmpty ()))
         {
            data [ count ]   =  heap . removeMin ();
            count ++ ;
         }
     }
}

Chap21/HeapSort/jsjf/ArrayBinaryTree.java

Chap21/HeapSort/jsjf/ArrayBinaryTree.java

package  jsjf ;

import  java . util . * ;
import  jsjf . exceptions . * ;

/**
 * ArrayBinaryTree implements the BinaryTreeADT interface using an array.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayBinaryTree < T >   implements   BinaryTreeADT < T > ,   Iterable < T >
{
     private   static   final   int  DEFAULT_CAPACITY  =   50 ;

     protected   int  count ;
     protected  T []  tree ;  
     protected   int  modCount ;

     /**
     * Creates an empty binary tree.
     */
     public   ArrayBinaryTree ()  
     {
        count  =   0 ;
        tree  =   ( T [])   new   Object [ DEFAULT_CAPACITY ];
     }

     /**
     * Creates a binary tree with the specified element as its root.
     *
     *  @param  element the element which will become the root of the new tree
     */
     public   ArrayBinaryTree ( T element )  
     {
        count  =   1 ;
        tree  =   ( T [])   new   Object [ DEFAULT_CAPACITY ];
        tree [ 0 ]   =  element ;
     }

     /**
     * Private method to expand capacity if full.
     */     
     protected   void  expandCapacity ()
     {
        tree  =   Arrays . copyOf ( tree ,  tree . length  *   2 );    
     }

     /**
     * Returns the root element of the tree.
     *
     *  @return  element stored at the root
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T getRootElement ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "ArrayBinaryTree" );

         return  tree [ 0 ];
     }

     /**
     * Returns true if this binary tree is empty and false otherwise.
     * 
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ()  
     {
         return   ( count  ==   0 );
     }

     /**
     * Returns the integer size of this binary tree.
     *
     *  @return  the integer size of this binary tree
     */
     public   int  size ()  
     {
         return  count ;
     }

     /**
     * Returns true if this tree contains an element that matches the
     * specified target element and false otherwise.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the element is in this tree
     */
     public   boolean  contains ( T targetElement )  
     {
        T temp ;
         boolean  found  =   false ;

         try  
         {
            temp  =  find ( targetElement );
            found  =   true ;
         }
         catch   ( Exception   ElementNotFoundException )  
         {
            found  =   false ;
         }

         return  found ;
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this binary tree.  Throws a ElementNotFoundException if
     * the specified target element is not found in the binary tree.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the element is in the tree
     *  @throws  ElementNotFoundException if the element is not in the tree
     */
     public  T find ( T targetElement )   throws   ElementNotFoundException  
     {
        T temp  =   null ;
         boolean  found  =   false ;

         for   ( int  i  =   0 ;  i  <  tree . length  &&   ! found ;  i ++ )
             if   ( tree [ i ]   !=   null )
                 if   ( targetElement . equals ( tree [ i ]))
                 {
                    found  =   true ;
                    temp  =  tree [ i ];
                 }

         if   ( ! found )
             throw   new   ElementNotFoundException ( "ArrayBinaryTree" );

         return  temp ;
     }


     /**
     * Returns a string representation of this binary tree showing
     * the nodes in an inorder fashion.
     *
     *  @return  a string representation of the binary tree
     */
     public   String  toString ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        inOrder ( 0 ,  tempList );

         return  tempList . toString ();
     }

     /**
     * Returns an iterator over the elements of this binary tree using
     * the iteratorInOrder method
     *
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iterator ()  
     {
         return   this . iteratorInOrder ();
     }

     /**
     * Performs an inorder traversal on this binary tree by calling an
     * overloaded, recursive inorder method that starts with
     * the root.
     *
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iteratorInOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        inOrder ( 0 ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive inorder traversal.
     *
     *  @param  node the index of the node used in the traversal
     *  @param  tempList the temporary list used in the traversal
     */
     protected   void  inOrder ( int  node ,   ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  <  tree . length )
             if   ( tree [ node ]   !=   null )
             {
                inOrder ( node  *   2   +   1 ,  tempList );
                tempList . addToRear ( tree [ node ]);
                inOrder (( node  +   1 )   *   2 ,  tempList );
             }
     }

     /**
     * Performs an preorder traversal on this binary tree by calling an
     * overloaded, recursive preorder method that starts with
     * the root.
     * 
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iteratorPreOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        preOrder ( 0 ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive preorder traversal.
     *
     *  @param  node the index of the node used in the traversal
     *  @param  tempList the temporary list used in the traversal
     */
     protected   void  preOrder ( int  node ,   ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  <  tree . length )
             if   ( tree [ node ]   !=   null )  
             {  
                tempList . addToRear ( tree [ node ]);
                preOrder ( node  *   2   +   1 ,  tempList );
                preOrder (( node  +   1 )   *   2 ,  tempList );
             }
     }

     /**
     * Performs an postorder traversal on the binary tree by calling
     * an overloaded, recursive postorder method that starts
     * with the root.
     * 
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iteratorPostOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        postOrder ( 0 ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive postorder traversal.
     * 
     *  @param  node the index of the node used in the traversal
     *  @param  tempList the temporary list used in the traversal
     */
     protected   void  postOrder ( int  node ,   ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  <  tree . length )
             if   ( tree [ node ]   !=   null )  
             {
                postOrder ( node  *   2   +   1 ,  tempList );  
                postOrder (( node  +   1 )   *   2 ,  tempList );
                tempList . addToRear ( tree [ node ]);   
             }
     }

     /**
     * Performs a levelorder traversal on this binary tree, using a
     * tempList.
     *
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
         int  ct  =   0 ;   // current number of elements added to list
         int  i  =   0 ;   // current position in array

         while   ( ct  <  count )
         {
             if   ( tree [ i ]   !=   null )
             {
                tempList . addToRear ( tree [ i ]);
                ct ++ ;
             }
            i ++ ;
         }

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Inner class to represent an iterator over the elements of this tree
     */
     private   class   TreeIterator   implements   Iterator < T >
     {
         private   int  expectedModCount ;
         private   Iterator < T >  iter ;

         /**
         * Sets up this iterator using the specified iterator.
         *
         *  @param  iter the list iterator created by a tree traversal
         */
         public   TreeIterator ( Iterator < T >  iter )
         {
             this . iter  =  iter ;
            expectedModCount  =  modCount ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( ! ( modCount  ==  expectedModCount ))
                 throw   new   ConcurrentModificationException ();

             return   ( iter . hasNext ());
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return  the next element in the iteration
         *  @throws  NoSuchElementException if the iterator is empty
         */
         public  T next ()   throws   NoSuchElementException
         {
             if   ( hasNext ())
                 return   ( iter . next ());
             else  
                 throw   new   NoSuchElementException ();
         }

         /**
         * The remove operation is not supported.
         * 
         *  @throws  UnsupportedOperationException if the remove operation is called
         */
         public   void  remove ()
         {
             throw   new   UnsupportedOperationException ();
         }
     }
}

Chap21/HeapSort/jsjf/ArrayHeap.java

Chap21/HeapSort/jsjf/ArrayHeap.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayHeap provides an array implementation of a minheap.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayHeap < T >   extends   ArrayBinaryTree < T >   implements   HeapADT < T >  
{
     /**
     * Creates an empty heap.
     */
     public   ArrayHeap ()  
     {
         super ();
     }

     /**
     * Adds the specified element to this heap in the appropriate
     * position according to its key value.  
     *
     *  @param  obj the element to be added to the heap
     */
     public   void  addElement ( T obj )  
     {
         if   ( count  ==  tree . length )
            expandCapacity ();

        tree [ count ]   =  obj ;
        count ++ ;
        modCount ++ ;

         if   ( count  >   1 )
            heapifyAdd ();
     }

     /**
     * Reorders this heap to maintain the ordering property after
     * adding a node.
     */
     private   void  heapifyAdd ()
     {
        T temp ;
         int  next  =  count  -   1 ;

        temp  =  tree [ next ];

         while   (( next  !=   0 )   &&  
                 ((( Comparable < T > ) temp ). compareTo ( tree [( next  -   1 )   /   2 ])   <   0 ))
         {

            tree [ next ]   =  tree [( next  -   1 )   /   2 ];
            next  =   ( next  -   1 )   /   2 ;
         }

        tree [ next ]   =  temp ;
     }

     /**
     * Remove the element with the lowest value in this heap and
     * returns a reference to it. Throws an EmptyCollectionException if
     * the heap is empty.
     *
     *  @return  a reference to the element with the lowest value in this heap
     *  @throws  EmptyCollectionException if the heap is empty
     */
     public  T removeMin ()   throws   EmptyCollectionException  
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "ArrayHeap" );

        T minElement  =  tree [ 0 ];
        tree [ 0 ]   =  tree [ count  -   1 ];
        heapifyRemove ();
        count -- ;
        modCount -- ;

         return  minElement ;
     }

     /**
     * Reorders this heap to maintain the ordering property
     * after the minimum element has been removed.
     */
     private   void  heapifyRemove ()
     {
        T temp ;
         int  node  =   0 ;
         int  left  =   1 ;
         int  right  =   2 ;
         int  next ;

         if   (( tree [ left ]   ==   null )   &&   ( tree [ right ]   ==   null ))
            next  =  count ;
         else   if   ( tree [ right ]   ==   null )
            next  =  left ;
         else   if   ((( Comparable < T > ) tree [ left ]). compareTo ( tree [ right ])   <   0 )
            next  =  left ;
         else
            next  =  right ;
        temp  =  tree [ node ];

         while   (( next  <  count )   &&  
                 ((( Comparable < T > ) tree [ next ]). compareTo ( temp )   <   0 ))
         {
            tree [ node ]   =  tree [ next ];
            node  =  next ;
            left  =   2   *  node  +   1 ;
            right  =   2   *   ( node  +   1 );
             if   (( tree [ left ]   ==   null )   &&   ( tree [ right ]   ==   null ))
                next  =  count ;
             else   if   ( tree [ right ]   ==   null )
                next  =  left ;
             else   if   ((( Comparable < T > ) tree [ left ]). compareTo ( tree [ right ])   <   0 )
                next  =  left ;
             else
                next  =  right ;
         }
        tree [ node ]   =  temp ;
     }

     /**
     * Returns the element with the lowest value in this heap.
     * Throws an EmptyCollectionException if the heap is empty.
     *
     *  @return  the element with the lowest value in this heap
     *  @throws  EmptyCollectionException if the heap is empty
     */
     public  T findMin ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "ArrayHeap" );

         return  tree [ 0 ];
     }
}


Chap21/HeapSort/jsjf/ArrayList.java

Chap21/HeapSort/jsjf/ArrayList.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . * ;

/**
 * ArrayList represents an array implementation of a list. The front of
 * the list is kept at array index 0. This class will be extended
 * to create a specific kind of list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   abstract   class   ArrayList < T >   implements   ListADT < T > ,   Iterable < T >
{
     private   final   static   int  DEFAULT_CAPACITY  =   100 ;
     private   final   static   int  NOT_FOUND  =   - 1 ;

     protected   int  rear ;
     protected  T []  list ;  
     protected   int  modCount ;

     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayList ()
     {
         this ( DEFAULT_CAPACITY );
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the integer value of the size of the array list
     */
     public   ArrayList ( int  initialCapacity )
     {
        rear  =   0 ;
        list  =   ( T [])( new   Object [ initialCapacity ]);
        modCount  =   0 ;
     }

     /**
     * Creates a new array to store the contents of this list with
     * twice the capacity of the old one. Called by descendant classes
     * that add elements to the list.
     */
     protected   void  expandCapacity ()
     {
         // To be completed as a Programming Project
     }

     /**
     * Removes and returns the last element in this list.
     *
     *  @return  the last element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeLast ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the first element in this list.
     *
     *  @return  the first element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeFirst ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the specified element.
     *
     *  @param   element the element to be removed and returned from the list
     *  @return  the removed elememt
     *  @throws  ElementNotFoundException if the element is not in the list
     */
     public  T remove ( T element )
     {
        T result ;
         int  index  =  find ( element );

         if   ( index  ==  NOT_FOUND )
             throw   new   ElementNotFoundException ( "ArrayList" );

        result  =  list [ index ];
        rear -- ;

         // shift the appropriate elements 
         for   ( int  scan  =  index ;  scan  <  rear ;  scan ++ )
            list [ scan ]   =  list [ scan + 1 ];

        list [ rear ]   =   null ;
        modCount ++ ;

         return  result ;
     }

     /**
     * Returns a reference to the element at the front of this list.
     * The element is not removed from the list.  Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the first element in the list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the element at the rear of this list.
     * The element is not removed from the list. Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the last element of this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T last ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this list contains the specified element.
     *
     *  @param  target the target element
     *  @return  true if the target is in the list, false otherwise 
     */
     public   boolean  contains ( T target )
     {
         return   ( find ( target )   !=  NOT_FOUND );
     }

     /**
     * Returns the array index of the specified element, or the
     * constant NOT_FOUND if it is not found.
     *
     *  @param  target the target element
     *  @return  the index of the target element, or the 
     *         NOT_FOUND constant
     */
     private   int  find ( T target )
     {
         int  scan  =   0 ;  
         int  result  =  NOT_FOUND ;

         if   ( ! isEmpty ())
             while   ( result  ==  NOT_FOUND  &&  scan  <  rear )
                 if   ( target . equals ( list [ scan ]))
                    result  =  scan ;
                 else
                    scan ++ ;

         return  result ;
     }

     /**
     * Returns true if this list is empty and false otherwise. 
     *
     *  @return  true if the list is empty, false otherwise
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements currently in this list.
     *
     *  @return  the number of elements in the list
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this list. 
     * 
     *  @return  the string representation of the list
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }

     /**
     * Returns an iterator for the elements currently in this list.
     * 
     *  @return  an iterator for the elements in the list
     */
     public   Iterator < T >  iterator ()
     {
         return   new   ArrayListIterator ();
     }

     /**
     * ArrayListIterator iterator over the elements of an ArrayList.
     */  
     private   class   ArrayListIterator   implements   Iterator < T >
     {
         int  iteratorModCount ;
         int  current ;

         /**
         * Sets up this iterator using the specified modCount.
         * 
         *  @param  modCount the current modification count for the ArrayList
         */
         public   ArrayListIterator ()
         {
            iteratorModCount  =  modCount ;
            current  =   0 ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( iteratorModCount  !=  modCount )
                 throw   new   ConcurrentModificationException ();

             return   ( current  <  rear );
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return   the next element in the iteration
         *  @throws   NoSuchElementException if an element not found exception occurs
         *  @throws   ConcurrentModificationException if the collection has changed
         */
         public  T next ()   throws   ConcurrentModificationException
         {
             if   ( ! hasNext ())
                 throw   new   NoSuchElementException ();

            current ++ ;

             return  list [ current  -   1 ];
         }

         /**
         * The remove operation is not supported in this collection.
         * 
         *  @throws  UnsupportedOperationException if the remove method is called
         */
         public   void  remove ()   throws   UnsupportedOperationException
         {
             throw   new   UnsupportedOperationException ();
         }

     }    
}

Chap21/HeapSort/jsjf/ArrayUnorderedList.java

Chap21/HeapSort/jsjf/ArrayUnorderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayUnorderedList represents an array implementation of an unordered list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayUnorderedList < T >   extends   ArrayList < T >  
implements   UnorderedListADT < T >
{
     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayUnorderedList ()
     {
         super ();
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the initial size of the list
     */
     public   ArrayUnorderedList ( int  initialCapacity )
     {
         super ( initialCapacity );
     }

     /**
     * Adds the specified element to the front of this list.
     * 
     *  @param  element the element to be added to the front of the list
     */
     public   void  addToFront ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element to the rear of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToRear ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element after the specified target element.
     * Throws an ElementNotFoundException if the target is not found.
     *
     *  @param  element the element to be added after the target element
     *  @param  target  the target that the element is to be added after
     */
     public   void  addAfter ( T element ,  T target )
     {
         if   ( size ()   ==  list . length )
            expandCapacity ();

         int  scan  =   0 ;

         // find the insertion point
         while   ( scan  <  rear  &&   ! target . equals ( list [ scan ]))  
            scan ++ ;

         if   ( scan  ==  rear )
             throw   new   ElementNotFoundException ( "UnorderedList" );

        scan ++ ;

         // shift elements up one
         for   ( int  shift  =  rear ;  shift  >  scan ;  shift -- )
            list [ shift ]   =  list [ shift  -   1 ];

         // insert element
        list [ scan ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }
}

Chap21/HeapSort/jsjf/BinaryTreeADT.java

Chap21/HeapSort/jsjf/BinaryTreeADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * BinaryTreeADT defines the interface to a binary tree data structure.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   BinaryTreeADT < T >  
{
     /** 
     * Returns a reference to the root element 
     *
     *  @return  a reference to the root
     */
     public  T getRootElement ();

     /** 
     * Returns true if this binary tree is empty and false otherwise.
     *
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ();

     /** 
     * Returns the number of elements in this binary tree.
     *
     *  @return  the number of elements in the tree
     */
     public   int  size ();

     /** 
     * Returns true if the binary tree contains an element that matches
     * the specified element and false otherwise. 
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the tree contains the target element
     */
     public   boolean  contains ( T targetElement );

     /** 
     * Returns a reference to the specified element if it is found in 
     * this binary tree. Throws an exception if the specified element
     * is not found.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  a reference to the specified element
     */
     public  T find ( T targetElement );

     /**  
     * Returns the string representation of this binary tree.
     *
     *  @return  a string representation of the binary tree
     */
     public   String  toString ();

     /**  
     * Returns an iterator over the elements of this tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns an iterator that represents an inorder traversal on this binary tree.  
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorInOrder ();

     /**  
     * Returns an iterator that represents a preorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPreOrder ();

     /**  
     * Returns an iterator that represents a postorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPostOrder ();

     /**  
     * Returns an iterator that represents a levelorder traversal on the binary tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ();
}

Chap21/HeapSort/jsjf/exceptions/ElementNotFoundException.java

Chap21/HeapSort/jsjf/exceptions/ElementNotFoundException.java

package  jsjf . exceptions ;

/**
 * ElementNotFoundException represents the situation in which a target element 
 * is not present in a collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ElementNotFoundException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     */
     public   ElementNotFoundException   ( String  collection )
     {
         super   ( "The target element is not in this "   +  collection );
     }
}

Chap21/HeapSort/jsjf/exceptions/EmptyCollectionException.java

Chap21/HeapSort/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " is empty." );
     }
}

Chap21/HeapSort/jsjf/exceptions/NonComparableElementException.java

Chap21/HeapSort/jsjf/exceptions/NonComparableElementException.java

package  jsjf . exceptions ;

/**
 * NonComparableElementException  represents the situation in which an attempt 
 * is made to add an element that is not comparable to an ordered collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   NonComparableElementException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     * 
     *  @param  collection  the exception message to deliver
     */
     public   NonComparableElementException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " requires Comparable elements." );
     }
}

Chap21/HeapSort/jsjf/HeapADT.java

Chap21/HeapSort/jsjf/HeapADT.java

package  jsjf ;

/**
 * HeapADT defines the interface to a Heap.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   HeapADT < T >   extends   BinaryTreeADT < T >  
{
     /** 
     * Adds the specified object to this heap. 
     *
     *  @param  obj the element to be added to the heap
     */    
     public   void  addElement ( T obj );

     /** 
     * Removes element with the lowest value from this heap. 
     *
     *  @return  the element with the lowest value from the heap
     */
     public  T removeMin ();

     /** 
     * Returns a reference to the element with the lowest value in 
     * this heap. 
     *
     *  @return  a reference to the element with the lowest value in the heap
     */
     public  T findMin ();
}


Chap21/HeapSort/jsjf/ListADT.java

Chap21/HeapSort/jsjf/ListADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * ListADT defines the interface to a general list collection. Specific
 * types of lists will extend this interface to complete the
 * set of necessary operations.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   ListADT < T >   extends   Iterable < T >
{
     /**  
     * Removes and returns the first element from this list. 
     * 
     *  @return  the first element from this list
     */
     public  T removeFirst ();

     /**  
     * Removes and returns the last element from this list. 
     *
     *  @return  the last element from this list
     */
     public  T removeLast ();

     /**  
     * Removes and returns the specified element from this list. 
     *
     *  @param  element the element to be removed from the list
     */
     public  T remove ( T element );

     /**  
     * Returns a reference to the first element in this list. 
     *
     *  @return  a reference to the first element in this list
     */
     public  T first ();

     /**  
     * Returns a reference to the last element in this list. 
     *
     *  @return  a reference to the last element in this list
     */
     public  T last ();

     /**  
     * Returns true if this list contains the specified target element. 
     *
     *  @param  target the target that is being sought in the list
     *  @return  true if the list contains this element
     */
     public   boolean  contains ( T target );

     /**  
     * Returns true if this list contains no elements. 
     *
     *  @return  true if this list contains no elements
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this list. 
     *
     *  @return  the integer representation of number of elements in this list
     */
     public   int  size ();

     /**  
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements in this list
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns a string representation of this list. 
     *
     *  @return  a string representation of this list
     */
     public   String  toString ();
}

Chap21/HeapSort/jsjf/UnorderedListADT.java

Chap21/HeapSort/jsjf/UnorderedListADT.java

package  jsjf ;

/**
 * UnorderedListADT defines the interface to an unordered list collection. 
 * Elements are stored in any order the user desires.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   UnorderedListADT < T >   extends   ListADT < T >
{
     /**  
     * Adds the specified element to the front of this list. 
     *
     *  @param  element the element to be added to the front of this list    
     */
     public   void  addToFront ( T element );   

     /**  
     * Adds the specified element to the rear of this list. 
     *
     *  @param  element the element to be added to the rear of this list    
     */
     public   void  addToRear ( T element );  

     /**  
     * Adds the specified element after the specified target. 
     *
     *  @param  element the element to be added after the target
     *  @param  target  the target is the item that the element will be added
     *                after    
     */
     public   void  addAfter ( T element ,  T target );
}

Chap21/HeapSort/SortPhoneList.java

Chap21/HeapSort/SortPhoneList.java

/**
 * SortPhoneList driver for testing a heap sort.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   SortPhoneList
{
     /**
     * Creates an array of Contact objects, sorts them, then prints
     * them.
     */
     public   static   void  main ( String []  args )
     {
         Contact []  friends  =   new   Contact [ 7 ];

        friends [ 0 ]   =   new   Contact ( "John" ,   "Smith" ,   "610-555-7384" );
        friends [ 1 ]   =   new   Contact ( "Sarah" ,   "Barnes" ,   "215-555-3827" );
        friends [ 2 ]   =   new   Contact ( "Mark" ,   "Riley" ,   "733-555-2969" );
        friends [ 3 ]   =   new   Contact ( "Laura" ,   "Getz" ,   "663-555-3984" );
        friends [ 4 ]   =   new   Contact ( "Larry" ,   "Smith" ,   "464-555-3489" );
        friends [ 5 ]   =   new   Contact ( "Frank" ,   "Phelps" ,   "322-555-2284" );
        friends [ 6 ]   =   new   Contact ( "Marsha" ,   "Grant" ,   "243-555-2837" );

         HeapSort < Contact >  sort  =   new   HeapSort < Contact > ();
        sort . heapSort ( friends );

         for   ( Contact  friend  :  friends )
             System . out . println ( friend );
     }
}

Chap21/LinkedHeap/jsjf/ArrayList.java

Chap21/LinkedHeap/jsjf/ArrayList.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . * ;

/**
 * ArrayList represents an array implementation of a list. The front of
 * the list is kept at array index 0. This class will be extended
 * to create a specific kind of list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   abstract   class   ArrayList < T >   implements   ListADT < T > ,   Iterable < T >
{
     private   final   static   int  DEFAULT_CAPACITY  =   100 ;
     private   final   static   int  NOT_FOUND  =   - 1 ;

     protected   int  rear ;
     protected  T []  list ;  
     protected   int  modCount ;

     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayList ()
     {
         this ( DEFAULT_CAPACITY );
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the integer value of the size of the array list
     */
     public   ArrayList ( int  initialCapacity )
     {
        rear  =   0 ;
        list  =   ( T [])( new   Object [ initialCapacity ]);
        modCount  =   0 ;
     }

     /**
     * Creates a new array to store the contents of this list with
     * twice the capacity of the old one. Called by descendant classes
     * that add elements to the list.
     */
     protected   void  expandCapacity ()
     {
         // To be completed as a Programming Project
     }

     /**
     * Removes and returns the last element in this list.
     *
     *  @return  the last element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeLast ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the first element in this list.
     *
     *  @return  the first element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeFirst ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the specified element.
     *
     *  @param   element the element to be removed and returned from the list
     *  @return  the removed elememt
     *  @throws  ElementNotFoundException if the element is not in the list
     */
     public  T remove ( T element )
     {
        T result ;
         int  index  =  find ( element );

         if   ( index  ==  NOT_FOUND )
             throw   new   ElementNotFoundException ( "ArrayList" );

        result  =  list [ index ];
        rear -- ;

         // shift the appropriate elements 
         for   ( int  scan  =  index ;  scan  <  rear ;  scan ++ )
            list [ scan ]   =  list [ scan + 1 ];

        list [ rear ]   =   null ;
        modCount ++ ;

         return  result ;
     }

     /**
     * Returns a reference to the element at the front of this list.
     * The element is not removed from the list.  Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the first element in the list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the element at the rear of this list.
     * The element is not removed from the list. Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the last element of this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T last ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this list contains the specified element.
     *
     *  @param  target the target element
     *  @return  true if the target is in the list, false otherwise 
     */
     public   boolean  contains ( T target )
     {
         return   ( find ( target )   !=  NOT_FOUND );
     }

     /**
     * Returns the array index of the specified element, or the
     * constant NOT_FOUND if it is not found.
     *
     *  @param  target the target element
     *  @return  the index of the target element, or the 
     *         NOT_FOUND constant
     */
     private   int  find ( T target )
     {
         int  scan  =   0 ;  
         int  result  =  NOT_FOUND ;

         if   ( ! isEmpty ())
             while   ( result  ==  NOT_FOUND  &&  scan  <  rear )
                 if   ( target . equals ( list [ scan ]))
                    result  =  scan ;
                 else
                    scan ++ ;

         return  result ;
     }

     /**
     * Returns true if this list is empty and false otherwise. 
     *
     *  @return  true if the list is empty, false otherwise
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements currently in this list.
     *
     *  @return  the number of elements in the list
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this list. 
     * 
     *  @return  the string representation of the list
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }

     /**
     * Returns an iterator for the elements currently in this list.
     * 
     *  @return  an iterator for the elements in the list
     */
     public   Iterator < T >  iterator ()
     {
         return   new   ArrayListIterator ();
     }

     /**
     * ArrayListIterator iterator over the elements of an ArrayList.
     */  
     private   class   ArrayListIterator   implements   Iterator < T >
     {
         int  iteratorModCount ;
         int  current ;

         /**
         * Sets up this iterator using the specified modCount.
         * 
         *  @param  modCount the current modification count for the ArrayList
         */
         public   ArrayListIterator ()
         {
            iteratorModCount  =  modCount ;
            current  =   0 ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( iteratorModCount  !=  modCount )
                 throw   new   ConcurrentModificationException ();

             return   ( current  <  rear );
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return   the next element in the iteration
         *  @throws   NoSuchElementException if an element not found exception occurs
         *  @throws   ConcurrentModificationException if the collection has changed
         */
         public  T next ()   throws   ConcurrentModificationException
         {
             if   ( ! hasNext ())
                 throw   new   NoSuchElementException ();

            current ++ ;

             return  list [ current  -   1 ];
         }

         /**
         * The remove operation is not supported in this collection.
         * 
         *  @throws  UnsupportedOperationException if the remove method is called
         */
         public   void  remove ()   throws   UnsupportedOperationException
         {
             throw   new   UnsupportedOperationException ();
         }

     }    
}

Chap21/LinkedHeap/jsjf/ArrayUnorderedList.java

Chap21/LinkedHeap/jsjf/ArrayUnorderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayUnorderedList represents an array implementation of an unordered list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayUnorderedList < T >   extends   ArrayList < T >  
implements   UnorderedListADT < T >
{
     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayUnorderedList ()
     {
         super ();
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the initial size of the list
     */
     public   ArrayUnorderedList ( int  initialCapacity )
     {
         super ( initialCapacity );
     }

     /**
     * Adds the specified element to the front of this list.
     * 
     *  @param  element the element to be added to the front of the list
     */
     public   void  addToFront ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element to the rear of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToRear ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element after the specified target element.
     * Throws an ElementNotFoundException if the target is not found.
     *
     *  @param  element the element to be added after the target element
     *  @param  target  the target that the element is to be added after
     */
     public   void  addAfter ( T element ,  T target )
     {
         if   ( size ()   ==  list . length )
            expandCapacity ();

         int  scan  =   0 ;

         // find the insertion point
         while   ( scan  <  rear  &&   ! target . equals ( list [ scan ]))  
            scan ++ ;

         if   ( scan  ==  rear )
             throw   new   ElementNotFoundException ( "UnorderedList" );

        scan ++ ;

         // shift elements up one
         for   ( int  shift  =  rear ;  shift  >  scan ;  shift -- )
            list [ shift ]   =  list [ shift  -   1 ];

         // insert element
        list [ scan ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }
}

Chap21/LinkedHeap/jsjf/BinaryTreeADT.java

Chap21/LinkedHeap/jsjf/BinaryTreeADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * BinaryTreeADT defines the interface to a binary tree data structure.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   BinaryTreeADT < T >  
{
     /** 
     * Returns a reference to the root element 
     *
     *  @return  a reference to the root
     */
     public  T getRootElement ();

     /** 
     * Returns true if this binary tree is empty and false otherwise.
     *
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ();

     /** 
     * Returns the number of elements in this binary tree.
     *
     *  @return  the number of elements in the tree
     */
     public   int  size ();

     /** 
     * Returns true if the binary tree contains an element that matches
     * the specified element and false otherwise. 
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the tree contains the target element
     */
     public   boolean  contains ( T targetElement );

     /** 
     * Returns a reference to the specified element if it is found in 
     * this binary tree. Throws an exception if the specified element
     * is not found.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  a reference to the specified element
     */
     public  T find ( T targetElement );

     /**  
     * Returns the string representation of this binary tree.
     *
     *  @return  a string representation of the binary tree
     */
     public   String  toString ();

     /**  
     * Returns an iterator over the elements of this tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns an iterator that represents an inorder traversal on this binary tree.  
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorInOrder ();

     /**  
     * Returns an iterator that represents a preorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPreOrder ();

     /**  
     * Returns an iterator that represents a postorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPostOrder ();

     /**  
     * Returns an iterator that represents a levelorder traversal on the binary tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ();
}

Chap21/LinkedHeap/jsjf/BinaryTreeNode.java

Chap21/LinkedHeap/jsjf/BinaryTreeNode.java

package  jsjf ;

/**
 * BinaryTreeNode represents a node in a binary tree with a left and 
 * right child.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   BinaryTreeNode < T >
{
     protected  T element ;
     protected   BinaryTreeNode < T >  left ,  right ;

     /**
     * Creates a new tree node with the specified data.
     *
     *  @param  obj the element that will become a part of the new tree node
     */
     public   BinaryTreeNode ( T obj )  
     {
        element  =  obj ;
        left  =   null ;
        right  =   null ;
     }

     /**
     * Creates a new tree node with the specified data.
     *
     *  @param  obj the element that will become a part of the new tree node
     *  @param  left the tree that will be the left subtree of this node
     *  @param  right the tree that will be the right subtree of this node
     */
     public   BinaryTreeNode ( T obj ,   LinkedBinaryTree < T >  left ,   LinkedBinaryTree < T >  right )  
     {
        element  =  obj ;
         if   ( left  ==   null )
             this . left  =   null ;
         else
             this . left  =  left . getRootNode ();

         if   ( right  ==   null )
             this . right  =   null ;
         else
             this . right  =  right . getRootNode ();
     }

     /**
     * Returns the number of non-null children of this node.
     *
     *  @return  the integer number of non-null children of this node 
     */
     public   int  numChildren ()  
     {
         int  children  =   0 ;

         if   ( left  !=   null )
            children  =   1   +  left . numChildren ();

         if   ( right  !=   null )
            children  =  children  +   1   +  right . numChildren ();

         return  children ;
     }

     /**
     * Return the element at this node.
     *
     *  @return  the element stored at this node
     */
     public  T getElement ()  
     {
         return  element ;
     }

     /**
     * Return the right child of this node.
     *
     *  @return  the right child of this node
     */
     public   BinaryTreeNode < T >  getRight ()  
     {
         return  right ;
     }

     /**
     * Sets the right child of this node.
     *
     *  @param  node the right child of this node
     */
     public   void  setRight ( BinaryTreeNode < T >  node )  
     {
        right  =  node ;
     }

     /**
     * Return the left child of this node.
     *
     *  @return  the left child of the node
     */
     public   BinaryTreeNode < T >  getLeft ()  
     {
         return  left ;
     }

     /**
     * Sets the left child of this node.
     *
     *  @param  node the left child of this node
     */
     public   void  setLeft ( BinaryTreeNode < T >  node )  
     {
        left  =  node ;
     }
}

Chap21/LinkedHeap/jsjf/exceptions/ElementNotFoundException.java

Chap21/LinkedHeap/jsjf/exceptions/ElementNotFoundException.java

package  jsjf . exceptions ;

/**
 * ElementNotFoundException represents the situation in which a target element 
 * is not present in a collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ElementNotFoundException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     */
     public   ElementNotFoundException   ( String  collection )
     {
         super   ( "The target element is not in this "   +  collection );
     }
}

Chap21/LinkedHeap/jsjf/exceptions/EmptyCollectionException.java

Chap21/LinkedHeap/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " is empty." );
     }
}

Chap21/LinkedHeap/jsjf/exceptions/NonComparableElementException.java

Chap21/LinkedHeap/jsjf/exceptions/NonComparableElementException.java

package  jsjf . exceptions ;

/**
 * NonComparableElementException  represents the situation in which an attempt 
 * is made to add an element that is not comparable to an ordered collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   NonComparableElementException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     * 
     *  @param  collection  the exception message to deliver
     */
     public   NonComparableElementException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " requires Comparable elements." );
     }
}

Chap21/LinkedHeap/jsjf/HeapADT.java

Chap21/LinkedHeap/jsjf/HeapADT.java

package  jsjf ;

/**
 * HeapADT defines the interface to a Heap.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   HeapADT < T >   extends   BinaryTreeADT < T >  
{
     /** 
     * Adds the specified object to this heap. 
     *
     *  @param  obj the element to be added to the heap
     */    
     public   void  addElement ( T obj );

     /** 
     * Removes element with the lowest value from this heap. 
     *
     *  @return  the element with the lowest value from the heap
     */
     public  T removeMin ();

     /** 
     * Returns a reference to the element with the lowest value in 
     * this heap. 
     *
     *  @return  a reference to the element with the lowest value in the heap
     */
     public  T findMin ();
}


Chap21/LinkedHeap/jsjf/HeapNode.java

Chap21/LinkedHeap/jsjf/HeapNode.java

package  jsjf ;

/**
 * HeapNode represents a binary tree node with a parent pointer for use 
 * in heaps.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   HeapNode < T >   extends   BinaryTreeNode < T >
{
     protected   HeapNode < T >  parent ;

     /**
     * Creates a new heap node with the specified data.
     * 
     *  @param  obj the data to be contained within the new heap node
     */
     public   HeapNode ( T obj )  
     {
         super ( obj );
        parent  =   null ;
     }

     /**
     * Return the parent of this node.
     *
     *  @return  the parent of the node
     */
     public   HeapNode < T >  getParent ()  
     {
         return  parent ;
     }

     /**
     * Sets the element stored at this node.
     *
     *  @param  the element to be stored 
     */
     public   void  setElement ( T obj )  
     {
        element  =  obj ;
     }

     /**
     * Sets the parent of this node.
     *
     *  @param  node the parent of the node
     */
     public   void  setParent ( HeapNode < T >  node )  
     {
        parent  =  node ;
     }
}


Chap21/LinkedHeap/jsjf/LinkedBinaryTree.java

Chap21/LinkedHeap/jsjf/LinkedBinaryTree.java

package  jsjf ;

import  java . util . * ;
import  jsjf . exceptions . * ;

/**
 * LinkedBinaryTree implements the BinaryTreeADT interface
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinkedBinaryTree < T >   implements   BinaryTreeADT < T > ,   Iterable < T >
{
     protected   BinaryTreeNode < T >  root ;  
     protected   int  modCount ;

     /**
     * Creates an empty binary tree.
     */
     public   LinkedBinaryTree ()  
     {
        root  =   null ;
     }

     /**
     * Creates a binary tree with the specified element as its root.
     *
     *  @param  element the element that will become the root of the binary tree
     */
     public   LinkedBinaryTree ( T element )  
     {
        root  =   new   BinaryTreeNode < T > ( element );
     }

     /**
     * Creates a binary tree with the specified element as its root and the 
     * given trees as its left child and right child
     *
     *  @param  element the element that will become the root of the binary tree
     *  @param  left the left subtree of this tree
     *  @param  right the right subtree of this tree
     */
     public   LinkedBinaryTree ( T element ,   LinkedBinaryTree < T >  left ,  
             LinkedBinaryTree < T >  right )  
     {
        root  =   new   BinaryTreeNode < T > ( element );
        root . setLeft ( left . root );
        root . setRight ( right . root );
     }

     /**
     * Returns a reference to the element at the root
     *
     *  @return  a reference to the specified target
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T getRootElement ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the node at the root
     *
     *  @return  a reference to the specified node
     *  @throws  EmptyCollectionException if the tree is empty
     */
     protected   BinaryTreeNode < T >  getRootNode ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the left subtree of the root of this tree.
     *
     *  @return  a link to the left subtree fo the tree
     */
     public   LinkedBinaryTree < T >  getLeft ()
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns the right subtree of the root of this tree.
     *
     *  @return  a link to the right subtree of the tree
     */
     public   LinkedBinaryTree < T >  getRight ()
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this binary tree is empty and false otherwise.
     *
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ()  
     {
         return   ( root  ==   null );
     }

     /**
     * Returns the integer size of this tree.
     *
     *  @return  the integer size of the tree
     */
     public   int  size ()  
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns the height of this tree.
     *
     *  @return  the height of the tree
     */
     public   int  getHeight ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns the height of the specified node.
     *
     *  @param  node the node from which to calculate the height
     *  @return  the height of the tree
     */
     private   int  height ( BinaryTreeNode < T >  node )  
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns true if this tree contains an element that matches the
     * specified target element and false otherwise.
     *
     *  @param  targetElement the element being sought in this tree
     *  @return  true if the element in is this tree, false otherwise
     */
     public   boolean  contains ( T targetElement )  
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this binary tree.  Throws a ElementNotFoundException if
     * the specified target element is not found in the binary tree.
     *
     *  @param  targetElement the element being sought in this tree
     *  @return  a reference to the specified target
     *  @throws  ElementNotFoundException if the element is not in the tree
     */
     public  T find ( T targetElement )   throws   ElementNotFoundException
     {
         BinaryTreeNode < T >  current  =  findNode ( targetElement ,  root );

         if   ( current  ==   null )
             throw   new   ElementNotFoundException ( "LinkedBinaryTree" );

         return   ( current . getElement ());
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this binary tree.
     *
     *  @param  targetElement the element being sought in this tree
     *  @param  next the element to begin searching from
     */
     private   BinaryTreeNode < T >  findNode ( T targetElement ,  
             BinaryTreeNode < T >  next )
     {
         if   ( next  ==   null )
             return   null ;

         if   ( next . getElement (). equals ( targetElement ))
             return  next ;

         BinaryTreeNode < T >  temp  =  findNode ( targetElement ,  next . getLeft ());

         if   ( temp  ==   null )
            temp  =  findNode ( targetElement ,  next . getRight ());

         return  temp ;
     }

     /**
     * Returns a string representation of this binary tree showing
     * the nodes in an inorder fashion.
     *
     *  @return  a string representation of this binary tree
     */
     public   String  toString ()  
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }

     /**
     * Returns an iterator over the elements in this tree using the 
     * iteratorInOrder method
     *
     *  @return  an in order iterator over this binary tree
     */
     public   Iterator < T >  iterator ()
     {
         return  iteratorInOrder ();
     }

     /**
     * Performs an inorder traversal on this binary tree by calling an
     * overloaded, recursive inorder method that starts with
     * the root.
     *
     *  @return  an in order iterator over this binary tree
     */
     public   Iterator < T >  iteratorInOrder ()
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        inOrder ( root ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive inorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  inOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  !=   null )
         {
            inOrder ( node . getLeft (),  tempList );
            tempList . addToRear ( node . getElement ());
            inOrder ( node . getRight (),  tempList );
         }
     }

     /**
     * Performs an preorder traversal on this binary tree by calling 
     * an overloaded, recursive preorder method that starts with
     * the root.
     *
     *  @return  a pre order iterator over this tree
     */
     public   Iterator < T >  iteratorPreOrder ()  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Performs a recursive preorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  preOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         // To be completed as a Programming Project
     }

     /**
     * Performs an postorder traversal on this binary tree by calling
     * an overloaded, recursive postorder method that starts
     * with the root.
     *
     *  @return  a post order iterator over this tree
     */
     public   Iterator < T >  iteratorPostOrder ()  
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Performs a recursive postorder traversal.
     *
     *  @param  node the node to be used as the root for this traversal
     *  @param  tempList the temporary list for use in this traversal
     */
     protected   void  postOrder ( BinaryTreeNode < T >  node ,  
             ArrayUnorderedList < T >  tempList )  
     {
         // To be completed as a Programming Project
     }

     /**
     * Performs a levelorder traversal on this binary tree, using a
     * templist.
     *
     *  @return  a levelorder iterator over this binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ()  
     {
         ArrayUnorderedList < BinaryTreeNode < T >>  nodes  =  
                 new   ArrayUnorderedList < BinaryTreeNode < T >> ();
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
         BinaryTreeNode < T >  current ;

        nodes . addToRear ( root );

         while   ( ! nodes . isEmpty ())  
         {
            current  =  nodes . removeFirst ();

             if   ( current  !=   null )
             {
                tempList . addToRear ( current . getElement ());
                 if   ( current . getLeft ()   !=   null )
                    nodes . addToRear ( current . getLeft ());
                 if   ( current . getRight ()   !=   null )
                    nodes . addToRear ( current . getRight ());
             }
             else
                tempList . addToRear ( null );
         }

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Inner class to represent an iterator over the elements of this tree
     */
     private   class   TreeIterator   implements   Iterator < T >
     {
         private   int  expectedModCount ;
         private   Iterator < T >  iter ;

         /**
         * Sets up this iterator using the specified iterator.
         *
         *  @param  iter the list iterator created by a tree traversal
         */
         public   TreeIterator ( Iterator < T >  iter )
         {
             this . iter  =  iter ;
            expectedModCount  =  modCount ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( ! ( modCount  ==  expectedModCount ))
                 throw   new   ConcurrentModificationException ();

             return   ( iter . hasNext ());
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return  the next element in the iteration
         *  @throws  NoSuchElementException if the iterator is empty
         */
         public  T next ()   throws   NoSuchElementException
         {
             if   ( hasNext ())
                 return   ( iter . next ());
             else  
                 throw   new   NoSuchElementException ();
         }

         /**
         * The remove operation is not supported.
         * 
         *  @throws  UnsupportedOperationException if the remove operation is called
         */
         public   void  remove ()
         {
             throw   new   UnsupportedOperationException ();
         }
     }
}

Chap21/LinkedHeap/jsjf/LinkedHeap.java

Chap21/LinkedHeap/jsjf/LinkedHeap.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * LinkedHeap implements a heap.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   LinkedHeap < T >   extends   LinkedBinaryTree < T >   implements   HeapADT < T >  
{
     public   HeapNode < T >  lastNode ;   

     public   LinkedHeap ()  
     {
         super ();
     }

     /**
     * Adds the specified element to this heap in the appropriate
     * position according to its key value. 
     *
     *  @param  obj the element to be added to the heap
     */
     public   void  addElement ( T obj )  
     {
         HeapNode < T >  node  =   new   HeapNode < T > ( obj );

         if   ( root  ==   null )
            root = node ;
         else
         {
             HeapNode < T >  nextParent  =  getNextParentAdd ();  
             if   ( nextParent . getLeft ()   ==   null )
                nextParent . setLeft ( node );
             else
                nextParent . setRight ( node );

            node . setParent ( nextParent );
         }
        lastNode  =  node ;
        modCount ++ ;

         if   ( size ()   >   1 )
            heapifyAdd ();
     }

     /**
     * Returns the node that will be the parent of the new node
     *
     *  @return  the node that will be the parent of the new node
     */
     private   HeapNode < T >  getNextParentAdd ()
     {
         HeapNode < T >  result  =  lastNode ;

         while   (( result  !=  root )   &&   ( result . getParent (). getLeft ()   !=  result ))
            result  =  result . getParent ();

         if   ( result  !=  root )
             if   ( result . getParent (). getRight ()   ==   null )
                result  =  result . getParent ();
             else
             {
                result  =   ( HeapNode < T > ) result . getParent (). getRight ();
                 while   ( result . getLeft ()   !=   null )
                    result  =   ( HeapNode < T > ) result . getLeft ();
             }
         else
             while   ( result . getLeft ()   !=   null )
                result  =   ( HeapNode < T > ) result . getLeft ();

         return  result ;
     }

     /**
     * Reorders this heap after adding a node.
     */
     private   void  heapifyAdd ()
     {
        T temp ;
         HeapNode < T >  next  =  lastNode ;

        temp  =  next . getElement ();

         while   (( next  !=  root )   &&  
                 ((( Comparable < T > ) temp ). compareTo ( next . getParent (). getElement ())   <   0 ))
         {
            next . setElement ( next . getParent (). getElement ());
            next  =  next . parent ;
         }
        next . setElement ( temp );
     }

     /**
     * Remove the element with the lowest value in this heap and
     * returns a reference to it. Throws an EmptyCollectionException 
     * if the heap is empty.
     *
     *  @return  the element with the lowest value in this heap
     *  @throws  EmptyCollectionException if the heap is empty
     */
     public  T removeMin ()   throws   EmptyCollectionException  
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "LinkedHeap" );

        T minElement  =   root . getElement ();

         if   ( size ()   ==   1 )
         {
            root  =   null ;
            lastNode  =   null ;
         }
         else
         {
             HeapNode < T >  nextLast  =  getNewLastNode ();
             if   ( lastNode . getParent (). getLeft ()   ==  lastNode )
                lastNode . getParent (). setLeft ( null );
             else
                lastNode . getParent (). setRight ( null );

             (( HeapNode < T > ) root ). setElement ( lastNode . getElement ());
            lastNode  =  nextLast ;
            heapifyRemove ();
         }

        modCount ++ ;

         return  minElement ;
     }

     /**
     * Reorders this heap after removing the root element.
     */
     private   void  heapifyRemove ()
     {
        T temp ;
         HeapNode < T >  node  =   ( HeapNode < T > ) root ;
         HeapNode < T >  left  =   ( HeapNode < T > ) node . getLeft ();
         HeapNode < T >  right  =   ( HeapNode < T > ) node . getRight ();
         HeapNode < T >  next ;

         if   (( left  ==   null )   &&   ( right  ==   null ))
            next  =   null ;
         else   if   ( right  ==   null )
            next  =  left ;
         else   if   ((( Comparable < T > ) left . getElement ()). compareTo ( right . getElement ())   <   0 )
            next  =  left ;
         else
            next  =  right ;

        temp  =  node . getElement ();
         while   (( next  !=   null )   &&  
                 ((( Comparable < T > ) next . getElement ()). compareTo ( temp )   <   0 ))
         {
            node . setElement ( next . getElement ());
            node  =  next ;
            left  =   ( HeapNode < T > ) node . getLeft ();
            right  =   ( HeapNode < T > ) node . getRight ();

             if   (( left  ==   null )   &&   ( right  ==   null ))
                next  =   null ;
             else   if   ( right  ==   null )
                next  =  left ;
             else   if   ((( Comparable < T > ) left . getElement ()). compareTo ( right . getElement ())   <   0 )
                next  =  left ;
             else
                next  =  right ;
         }
        node . setElement ( temp );
     }

     /**
     * Returns the node that will be the new last node after a remove.
     *
     *  @return  the node that will be the new last node after a remove
     */
     private   HeapNode < T >  getNewLastNode ()
     {
         HeapNode < T >  result  =  lastNode ;

         while   (( result  !=  root )   &&   ( result . getParent (). getLeft ()   ==  result ))
            result  =  result . getParent ();

         if   ( result  !=  root )
            result  =   ( HeapNode < T > ) result . getParent (). getLeft ();

         while   ( result . getRight ()   !=   null )
            result  =   ( HeapNode < T > ) result . getRight ();

         return  result ;
     }

     /**
     * Returns the element with the lowest value in this heap.
     * Throws an EmptyCollectionException if the heap is empty.
     *
     *  @return  the element with the lowest value in this heap
     *  @throws  EmptyCollectionException if the heap is empty
     */
     public  T findMin ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "LinkedHeap" );

         return  root . getElement ();
     }
}

Chap21/LinkedHeap/jsjf/ListADT.java

Chap21/LinkedHeap/jsjf/ListADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * ListADT defines the interface to a general list collection. Specific
 * types of lists will extend this interface to complete the
 * set of necessary operations.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   ListADT < T >   extends   Iterable < T >
{
     /**  
     * Removes and returns the first element from this list. 
     * 
     *  @return  the first element from this list
     */
     public  T removeFirst ();

     /**  
     * Removes and returns the last element from this list. 
     *
     *  @return  the last element from this list
     */
     public  T removeLast ();

     /**  
     * Removes and returns the specified element from this list. 
     *
     *  @param  element the element to be removed from the list
     */
     public  T remove ( T element );

     /**  
     * Returns a reference to the first element in this list. 
     *
     *  @return  a reference to the first element in this list
     */
     public  T first ();

     /**  
     * Returns a reference to the last element in this list. 
     *
     *  @return  a reference to the last element in this list
     */
     public  T last ();

     /**  
     * Returns true if this list contains the specified target element. 
     *
     *  @param  target the target that is being sought in the list
     *  @return  true if the list contains this element
     */
     public   boolean  contains ( T target );

     /**  
     * Returns true if this list contains no elements. 
     *
     *  @return  true if this list contains no elements
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this list. 
     *
     *  @return  the integer representation of number of elements in this list
     */
     public   int  size ();

     /**  
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements in this list
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns a string representation of this list. 
     *
     *  @return  a string representation of this list
     */
     public   String  toString ();
}

Chap21/LinkedHeap/jsjf/UnorderedListADT.java

Chap21/LinkedHeap/jsjf/UnorderedListADT.java

package  jsjf ;

/**
 * UnorderedListADT defines the interface to an unordered list collection. 
 * Elements are stored in any order the user desires.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   UnorderedListADT < T >   extends   ListADT < T >
{
     /**  
     * Adds the specified element to the front of this list. 
     *
     *  @param  element the element to be added to the front of this list    
     */
     public   void  addToFront ( T element );   

     /**  
     * Adds the specified element to the rear of this list. 
     *
     *  @param  element the element to be added to the rear of this list    
     */
     public   void  addToRear ( T element );  

     /**  
     * Adds the specified element after the specified target. 
     *
     *  @param  element the element to be added after the target
     *  @param  target  the target is the item that the element will be added
     *                after    
     */
     public   void  addAfter ( T element ,  T target );
}

Chap21/PriorityQueue/jsjf/ArrayBinaryTree.java

Chap21/PriorityQueue/jsjf/ArrayBinaryTree.java

package  jsjf ;

import  java . util . * ;
import  jsjf . exceptions . * ;

/**
 * ArrayBinaryTree implements the BinaryTreeADT interface using an array.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayBinaryTree < T >   implements   BinaryTreeADT < T > ,   Iterable < T >
{
     private   static   final   int  DEFAULT_CAPACITY  =   50 ;

     protected   int  count ;
     protected  T []  tree ;  
     protected   int  modCount ;

     /**
     * Creates an empty binary tree.
     */
     public   ArrayBinaryTree ()  
     {
        count  =   0 ;
        tree  =   ( T [])   new   Object [ DEFAULT_CAPACITY ];
     }

     /**
     * Creates a binary tree with the specified element as its root.
     *
     *  @param  element the element which will become the root of the new tree
     */
     public   ArrayBinaryTree ( T element )  
     {
        count  =   1 ;
        tree  =   ( T [])   new   Object [ DEFAULT_CAPACITY ];
        tree [ 0 ]   =  element ;
     }

     /**
     * Private method to expand capacity if full.
     */     
     protected   void  expandCapacity ()
     {
        tree  =   Arrays . copyOf ( tree ,  tree . length  *   2 );    
     }

     /**
     * Returns the root element of the tree.
     *
     *  @return  element stored at the root
     *  @throws  EmptyCollectionException if the tree is empty
     */
     public  T getRootElement ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "ArrayBinaryTree" );

         return  tree [ 0 ];
     }

     /**
     * Returns true if this binary tree is empty and false otherwise.
     * 
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ()  
     {
         return   ( count  ==   0 );
     }

     /**
     * Returns the integer size of this binary tree.
     *
     *  @return  the integer size of this binary tree
     */
     public   int  size ()  
     {
         return  count ;
     }

     /**
     * Returns true if this tree contains an element that matches the
     * specified target element and false otherwise.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the element is in this tree
     */
     public   boolean  contains ( T targetElement )  
     {
        T temp ;
         boolean  found  =   false ;

         try  
         {
            temp  =  find ( targetElement );
            found  =   true ;
         }
         catch   ( Exception   ElementNotFoundException )  
         {
            found  =   false ;
         }

         return  found ;
     }

     /**
     * Returns a reference to the specified target element if it is
     * found in this binary tree.  Throws a ElementNotFoundException if
     * the specified target element is not found in the binary tree.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the element is in the tree
     *  @throws  ElementNotFoundException if the element is not in the tree
     */
     public  T find ( T targetElement )   throws   ElementNotFoundException  
     {
        T temp  =   null ;
         boolean  found  =   false ;

         for   ( int  i  =   0 ;  i  <  tree . length  &&   ! found ;  i ++ )
             if   ( tree [ i ]   !=   null )
                 if   ( targetElement . equals ( tree [ i ]))
                 {
                    found  =   true ;
                    temp  =  tree [ i ];
                 }

         if   ( ! found )
             throw   new   ElementNotFoundException ( "ArrayBinaryTree" );

         return  temp ;
     }


     /**
     * Returns a string representation of this binary tree showing
     * the nodes in an inorder fashion.
     *
     *  @return  a string representation of the binary tree
     */
     public   String  toString ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        inOrder ( 0 ,  tempList );

         return  tempList . toString ();
     }

     /**
     * Returns an iterator over the elements of this binary tree using
     * the iteratorInOrder method
     *
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iterator ()  
     {
         return   this . iteratorInOrder ();
     }

     /**
     * Performs an inorder traversal on this binary tree by calling an
     * overloaded, recursive inorder method that starts with
     * the root.
     *
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iteratorInOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        inOrder ( 0 ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive inorder traversal.
     *
     *  @param  node the index of the node used in the traversal
     *  @param  tempList the temporary list used in the traversal
     */
     protected   void  inOrder ( int  node ,   ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  <  tree . length )
             if   ( tree [ node ]   !=   null )
             {
                inOrder ( node  *   2   +   1 ,  tempList );
                tempList . addToRear ( tree [ node ]);
                inOrder (( node  +   1 )   *   2 ,  tempList );
             }
     }

     /**
     * Performs an preorder traversal on this binary tree by calling an
     * overloaded, recursive preorder method that starts with
     * the root.
     * 
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iteratorPreOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        preOrder ( 0 ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive preorder traversal.
     *
     *  @param  node the index of the node used in the traversal
     *  @param  tempList the temporary list used in the traversal
     */
     protected   void  preOrder ( int  node ,   ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  <  tree . length )
             if   ( tree [ node ]   !=   null )  
             {  
                tempList . addToRear ( tree [ node ]);
                preOrder ( node  *   2   +   1 ,  tempList );
                preOrder (( node  +   1 )   *   2 ,  tempList );
             }
     }

     /**
     * Performs an postorder traversal on the binary tree by calling
     * an overloaded, recursive postorder method that starts
     * with the root.
     * 
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iteratorPostOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
        postOrder ( 0 ,  tempList );

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Performs a recursive postorder traversal.
     * 
     *  @param  node the index of the node used in the traversal
     *  @param  tempList the temporary list used in the traversal
     */
     protected   void  postOrder ( int  node ,   ArrayUnorderedList < T >  tempList )  
     {
         if   ( node  <  tree . length )
             if   ( tree [ node ]   !=   null )  
             {
                postOrder ( node  *   2   +   1 ,  tempList );  
                postOrder (( node  +   1 )   *   2 ,  tempList );
                tempList . addToRear ( tree [ node ]);   
             }
     }

     /**
     * Performs a levelorder traversal on this binary tree, using a
     * tempList.
     *
     *  @return  an iterator over the binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ()  
     {
         ArrayUnorderedList < T >  tempList  =   new   ArrayUnorderedList < T > ();
         int  ct  =   0 ;   // current number of elements added to list
         int  i  =   0 ;   // current position in array

         while   ( ct  <  count )
         {
             if   ( tree [ i ]   !=   null )
             {
                tempList . addToRear ( tree [ i ]);
                ct ++ ;
             }
            i ++ ;
         }

         return   new   TreeIterator ( tempList . iterator ());
     }

     /**
     * Inner class to represent an iterator over the elements of this tree
     */
     private   class   TreeIterator   implements   Iterator < T >
     {
         private   int  expectedModCount ;
         private   Iterator < T >  iter ;

         /**
         * Sets up this iterator using the specified iterator.
         *
         *  @param  iter the list iterator created by a tree traversal
         */
         public   TreeIterator ( Iterator < T >  iter )
         {
             this . iter  =  iter ;
            expectedModCount  =  modCount ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( ! ( modCount  ==  expectedModCount ))
                 throw   new   ConcurrentModificationException ();

             return   ( iter . hasNext ());
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return  the next element in the iteration
         *  @throws  NoSuchElementException if the iterator is empty
         */
         public  T next ()   throws   NoSuchElementException
         {
             if   ( hasNext ())
                 return   ( iter . next ());
             else  
                 throw   new   NoSuchElementException ();
         }

         /**
         * The remove operation is not supported.
         * 
         *  @throws  UnsupportedOperationException if the remove operation is called
         */
         public   void  remove ()
         {
             throw   new   UnsupportedOperationException ();
         }
     }
}

Chap21/PriorityQueue/jsjf/ArrayHeap.java

Chap21/PriorityQueue/jsjf/ArrayHeap.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayHeap provides an array implementation of a minheap.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayHeap < T >   extends   ArrayBinaryTree < T >   implements   HeapADT < T >  
{
     /**
     * Creates an empty heap.
     */
     public   ArrayHeap ()  
     {
         super ();
     }

     /**
     * Adds the specified element to this heap in the appropriate
     * position according to its key value.  
     *
     *  @param  obj the element to be added to the heap
     */
     public   void  addElement ( T obj )  
     {
         if   ( count  ==  tree . length )
            expandCapacity ();

        tree [ count ]   =  obj ;
        count ++ ;
        modCount ++ ;

         if   ( count  >   1 )
            heapifyAdd ();
     }

     /**
     * Reorders this heap to maintain the ordering property after
     * adding a node.
     */
     private   void  heapifyAdd ()
     {
        T temp ;
         int  next  =  count  -   1 ;

        temp  =  tree [ next ];

         while   (( next  !=   0 )   &&  
                 ((( Comparable < T > ) temp ). compareTo ( tree [( next  -   1 )   /   2 ])   <   0 ))
         {

            tree [ next ]   =  tree [( next  -   1 )   /   2 ];
            next  =   ( next  -   1 )   /   2 ;
         }

        tree [ next ]   =  temp ;
     }

     /**
     * Remove the element with the lowest value in this heap and
     * returns a reference to it. Throws an EmptyCollectionException if
     * the heap is empty.
     *
     *  @return  a reference to the element with the lowest value in this heap
     *  @throws  EmptyCollectionException if the heap is empty
     */
     public  T removeMin ()   throws   EmptyCollectionException  
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "ArrayHeap" );

        T minElement  =  tree [ 0 ];
        tree [ 0 ]   =  tree [ count  -   1 ];
        heapifyRemove ();
        count -- ;
        modCount -- ;

         return  minElement ;
     }

     /**
     * Reorders this heap to maintain the ordering property
     * after the minimum element has been removed.
     */
     private   void  heapifyRemove ()
     {
        T temp ;
         int  node  =   0 ;
         int  left  =   1 ;
         int  right  =   2 ;
         int  next ;

         if   (( tree [ left ]   ==   null )   &&   ( tree [ right ]   ==   null ))
            next  =  count ;
         else   if   ( tree [ right ]   ==   null )
            next  =  left ;
         else   if   ((( Comparable < T > ) tree [ left ]). compareTo ( tree [ right ])   <   0 )
            next  =  left ;
         else
            next  =  right ;
        temp  =  tree [ node ];

         while   (( next  <  count )   &&  
                 ((( Comparable < T > ) tree [ next ]). compareTo ( temp )   <   0 ))
         {
            tree [ node ]   =  tree [ next ];
            node  =  next ;
            left  =   2   *  node  +   1 ;
            right  =   2   *   ( node  +   1 );
             if   (( tree [ left ]   ==   null )   &&   ( tree [ right ]   ==   null ))
                next  =  count ;
             else   if   ( tree [ right ]   ==   null )
                next  =  left ;
             else   if   ((( Comparable < T > ) tree [ left ]). compareTo ( tree [ right ])   <   0 )
                next  =  left ;
             else
                next  =  right ;
         }
        tree [ node ]   =  temp ;
     }

     /**
     * Returns the element with the lowest value in this heap.
     * Throws an EmptyCollectionException if the heap is empty.
     *
     *  @return  the element with the lowest value in this heap
     *  @throws  EmptyCollectionException if the heap is empty
     */
     public  T findMin ()   throws   EmptyCollectionException
     {
         if   ( isEmpty ())
             throw   new   EmptyCollectionException ( "ArrayHeap" );

         return  tree [ 0 ];
     }
}


Chap21/PriorityQueue/jsjf/ArrayList.java

Chap21/PriorityQueue/jsjf/ArrayList.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . * ;

/**
 * ArrayList represents an array implementation of a list. The front of
 * the list is kept at array index 0. This class will be extended
 * to create a specific kind of list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   abstract   class   ArrayList < T >   implements   ListADT < T > ,   Iterable < T >
{
     private   final   static   int  DEFAULT_CAPACITY  =   100 ;
     private   final   static   int  NOT_FOUND  =   - 1 ;

     protected   int  rear ;
     protected  T []  list ;  
     protected   int  modCount ;

     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayList ()
     {
         this ( DEFAULT_CAPACITY );
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the integer value of the size of the array list
     */
     public   ArrayList ( int  initialCapacity )
     {
        rear  =   0 ;
        list  =   ( T [])( new   Object [ initialCapacity ]);
        modCount  =   0 ;
     }

     /**
     * Creates a new array to store the contents of this list with
     * twice the capacity of the old one. Called by descendant classes
     * that add elements to the list.
     */
     protected   void  expandCapacity ()
     {
         // To be completed as a Programming Project
     }

     /**
     * Removes and returns the last element in this list.
     *
     *  @return  the last element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeLast ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the first element in this list.
     *
     *  @return  the first element in the list
     *  @throws  EmptyCollectionException if the element is not in the list
     */
     public  T removeFirst ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Removes and returns the specified element.
     *
     *  @param   element the element to be removed and returned from the list
     *  @return  the removed elememt
     *  @throws  ElementNotFoundException if the element is not in the list
     */
     public  T remove ( T element )
     {
        T result ;
         int  index  =  find ( element );

         if   ( index  ==  NOT_FOUND )
             throw   new   ElementNotFoundException ( "ArrayList" );

        result  =  list [ index ];
        rear -- ;

         // shift the appropriate elements 
         for   ( int  scan  =  index ;  scan  <  rear ;  scan ++ )
            list [ scan ]   =  list [ scan + 1 ];

        list [ rear ]   =   null ;
        modCount ++ ;

         return  result ;
     }

     /**
     * Returns a reference to the element at the front of this list.
     * The element is not removed from the list.  Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the first element in the list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T first ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns a reference to the element at the rear of this list.
     * The element is not removed from the list. Throws an
     * EmptyCollectionException if the list is empty.  
     *
     *  @return  a reference to the last element of this list
     *  @throws  EmptyCollectionException if the list is empty
     */
     public  T last ()   throws   EmptyCollectionException
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }

     /**
     * Returns true if this list contains the specified element.
     *
     *  @param  target the target element
     *  @return  true if the target is in the list, false otherwise 
     */
     public   boolean  contains ( T target )
     {
         return   ( find ( target )   !=  NOT_FOUND );
     }

     /**
     * Returns the array index of the specified element, or the
     * constant NOT_FOUND if it is not found.
     *
     *  @param  target the target element
     *  @return  the index of the target element, or the 
     *         NOT_FOUND constant
     */
     private   int  find ( T target )
     {
         int  scan  =   0 ;  
         int  result  =  NOT_FOUND ;

         if   ( ! isEmpty ())
             while   ( result  ==  NOT_FOUND  &&  scan  <  rear )
                 if   ( target . equals ( list [ scan ]))
                    result  =  scan ;
                 else
                    scan ++ ;

         return  result ;
     }

     /**
     * Returns true if this list is empty and false otherwise. 
     *
     *  @return  true if the list is empty, false otherwise
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the number of elements currently in this list.
     *
     *  @return  the number of elements in the list
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns a string representation of this list. 
     * 
     *  @return  the string representation of the list
     */
     public   String  toString ()
     {
         // To be completed as a Programming Project
        
         return   "" ;    // temp
     }

     /**
     * Returns an iterator for the elements currently in this list.
     * 
     *  @return  an iterator for the elements in the list
     */
     public   Iterator < T >  iterator ()
     {
         return   new   ArrayListIterator ();
     }

     /**
     * ArrayListIterator iterator over the elements of an ArrayList.
     */  
     private   class   ArrayListIterator   implements   Iterator < T >
     {
         int  iteratorModCount ;
         int  current ;

         /**
         * Sets up this iterator using the specified modCount.
         * 
         *  @param  modCount the current modification count for the ArrayList
         */
         public   ArrayListIterator ()
         {
            iteratorModCount  =  modCount ;
            current  =   0 ;
         }

         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( iteratorModCount  !=  modCount )
                 throw   new   ConcurrentModificationException ();

             return   ( current  <  rear );
         }

         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return   the next element in the iteration
         *  @throws   NoSuchElementException if an element not found exception occurs
         *  @throws   ConcurrentModificationException if the collection has changed
         */
         public  T next ()   throws   ConcurrentModificationException
         {
             if   ( ! hasNext ())
                 throw   new   NoSuchElementException ();

            current ++ ;

             return  list [ current  -   1 ];
         }

         /**
         * The remove operation is not supported in this collection.
         * 
         *  @throws  UnsupportedOperationException if the remove method is called
         */
         public   void  remove ()   throws   UnsupportedOperationException
         {
             throw   new   UnsupportedOperationException ();
         }

     }    
}

Chap21/PriorityQueue/jsjf/ArrayUnorderedList.java

Chap21/PriorityQueue/jsjf/ArrayUnorderedList.java

package  jsjf ;

import  jsjf . exceptions . * ;

/**
 * ArrayUnorderedList represents an array implementation of an unordered list.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ArrayUnorderedList < T >   extends   ArrayList < T >  
implements   UnorderedListADT < T >
{
     /**
     * Creates an empty list using the default capacity.
     */
     public   ArrayUnorderedList ()
     {
         super ();
     }

     /**
     * Creates an empty list using the specified capacity.
     *
     *  @param  initialCapacity the initial size of the list
     */
     public   ArrayUnorderedList ( int  initialCapacity )
     {
         super ( initialCapacity );
     }

     /**
     * Adds the specified element to the front of this list.
     * 
     *  @param  element the element to be added to the front of the list
     */
     public   void  addToFront ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element to the rear of this list.
     *
     *  @param  element the element to be added to the list
     */
     public   void  addToRear ( T element )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds the specified element after the specified target element.
     * Throws an ElementNotFoundException if the target is not found.
     *
     *  @param  element the element to be added after the target element
     *  @param  target  the target that the element is to be added after
     */
     public   void  addAfter ( T element ,  T target )
     {
         if   ( size ()   ==  list . length )
            expandCapacity ();

         int  scan  =   0 ;

         // find the insertion point
         while   ( scan  <  rear  &&   ! target . equals ( list [ scan ]))  
            scan ++ ;

         if   ( scan  ==  rear )
             throw   new   ElementNotFoundException ( "UnorderedList" );

        scan ++ ;

         // shift elements up one
         for   ( int  shift  =  rear ;  shift  >  scan ;  shift -- )
            list [ shift ]   =  list [ shift  -   1 ];

         // insert element
        list [ scan ]   =  element ;
        rear ++ ;
        modCount ++ ;
     }
}

Chap21/PriorityQueue/jsjf/BinaryTreeADT.java

Chap21/PriorityQueue/jsjf/BinaryTreeADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * BinaryTreeADT defines the interface to a binary tree data structure.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   BinaryTreeADT < T >  
{
     /** 
     * Returns a reference to the root element 
     *
     *  @return  a reference to the root
     */
     public  T getRootElement ();

     /** 
     * Returns true if this binary tree is empty and false otherwise.
     *
     *  @return  true if this binary tree is empty, false otherwise
     */
     public   boolean  isEmpty ();

     /** 
     * Returns the number of elements in this binary tree.
     *
     *  @return  the number of elements in the tree
     */
     public   int  size ();

     /** 
     * Returns true if the binary tree contains an element that matches
     * the specified element and false otherwise. 
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  true if the tree contains the target element
     */
     public   boolean  contains ( T targetElement );

     /** 
     * Returns a reference to the specified element if it is found in 
     * this binary tree. Throws an exception if the specified element
     * is not found.
     *
     *  @param  targetElement the element being sought in the tree
     *  @return  a reference to the specified element
     */
     public  T find ( T targetElement );

     /**  
     * Returns the string representation of this binary tree.
     *
     *  @return  a string representation of the binary tree
     */
     public   String  toString ();

     /**  
     * Returns an iterator over the elements of this tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns an iterator that represents an inorder traversal on this binary tree.  
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorInOrder ();

     /**  
     * Returns an iterator that represents a preorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPreOrder ();

     /**  
     * Returns an iterator that represents a postorder traversal on this binary tree. 
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorPostOrder ();

     /**  
     * Returns an iterator that represents a levelorder traversal on the binary tree.
     *
     *  @return  an iterator over the elements of this binary tree
     */
     public   Iterator < T >  iteratorLevelOrder ();
}

Chap21/PriorityQueue/jsjf/exceptions/ElementNotFoundException.java

Chap21/PriorityQueue/jsjf/exceptions/ElementNotFoundException.java

package  jsjf . exceptions ;

/**
 * ElementNotFoundException represents the situation in which a target element 
 * is not present in a collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ElementNotFoundException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     */
     public   ElementNotFoundException   ( String  collection )
     {
         super   ( "The target element is not in this "   +  collection );
     }
}

Chap21/PriorityQueue/jsjf/exceptions/EmptyCollectionException.java

Chap21/PriorityQueue/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " is empty." );
     }
}

Chap21/PriorityQueue/jsjf/exceptions/NonComparableElementException.java

Chap21/PriorityQueue/jsjf/exceptions/NonComparableElementException.java

package  jsjf . exceptions ;

/**
 * NonComparableElementException  represents the situation in which an attempt 
 * is made to add an element that is not comparable to an ordered collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   NonComparableElementException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     * 
     *  @param  collection  the exception message to deliver
     */
     public   NonComparableElementException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " requires Comparable elements." );
     }
}

Chap21/PriorityQueue/jsjf/HeapADT.java

Chap21/PriorityQueue/jsjf/HeapADT.java

package  jsjf ;

/**
 * HeapADT defines the interface to a Heap.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   HeapADT < T >   extends   BinaryTreeADT < T >  
{
     /** 
     * Adds the specified object to this heap. 
     *
     *  @param  obj the element to be added to the heap
     */    
     public   void  addElement ( T obj );

     /** 
     * Removes element with the lowest value from this heap. 
     *
     *  @return  the element with the lowest value from the heap
     */
     public  T removeMin ();

     /** 
     * Returns a reference to the element with the lowest value in 
     * this heap. 
     *
     *  @return  a reference to the element with the lowest value in the heap
     */
     public  T findMin ();
}


Chap21/PriorityQueue/jsjf/ListADT.java

Chap21/PriorityQueue/jsjf/ListADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * ListADT defines the interface to a general list collection. Specific
 * types of lists will extend this interface to complete the
 * set of necessary operations.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   ListADT < T >   extends   Iterable < T >
{
     /**  
     * Removes and returns the first element from this list. 
     * 
     *  @return  the first element from this list
     */
     public  T removeFirst ();

     /**  
     * Removes and returns the last element from this list. 
     *
     *  @return  the last element from this list
     */
     public  T removeLast ();

     /**  
     * Removes and returns the specified element from this list. 
     *
     *  @param  element the element to be removed from the list
     */
     public  T remove ( T element );

     /**  
     * Returns a reference to the first element in this list. 
     *
     *  @return  a reference to the first element in this list
     */
     public  T first ();

     /**  
     * Returns a reference to the last element in this list. 
     *
     *  @return  a reference to the last element in this list
     */
     public  T last ();

     /**  
     * Returns true if this list contains the specified target element. 
     *
     *  @param  target the target that is being sought in the list
     *  @return  true if the list contains this element
     */
     public   boolean  contains ( T target );

     /**  
     * Returns true if this list contains no elements. 
     *
     *  @return  true if this list contains no elements
     */
     public   boolean  isEmpty ();

     /**  
     * Returns the number of elements in this list. 
     *
     *  @return  the integer representation of number of elements in this list
     */
     public   int  size ();

     /**  
     * Returns an iterator for the elements in this list. 
     *
     *  @return  an iterator over the elements in this list
     */
     public   Iterator < T >  iterator ();

     /**  
     * Returns a string representation of this list. 
     *
     *  @return  a string representation of this list
     */
     public   String  toString ();
}

Chap21/PriorityQueue/jsjf/UnorderedListADT.java

Chap21/PriorityQueue/jsjf/UnorderedListADT.java

package  jsjf ;

/**
 * UnorderedListADT defines the interface to an unordered list collection. 
 * Elements are stored in any order the user desires.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   UnorderedListADT < T >   extends   ListADT < T >
{
     /**  
     * Adds the specified element to the front of this list. 
     *
     *  @param  element the element to be added to the front of this list    
     */
     public   void  addToFront ( T element );   

     /**  
     * Adds the specified element to the rear of this list. 
     *
     *  @param  element the element to be added to the rear of this list    
     */
     public   void  addToRear ( T element );  

     /**  
     * Adds the specified element after the specified target. 
     *
     *  @param  element the element to be added after the target
     *  @param  target  the target is the item that the element will be added
     *                after    
     */
     public   void  addAfter ( T element ,  T target );
}

Chap21/PriorityQueue/PQTester.java

Chap21/PriorityQueue/PQTester.java

/** 
 * Tests a priority queue.
 * 
 *  @author  Java Foundations
 */
public   class   PQTester
{
     public   static   void  main ( String []  args )
     {
         PriorityQueue < String >  pq  =   new   PriorityQueue < String > ();
        
        pq . addElement ( "this one should be last" ,   99 );
        pq . addElement ( "first" ,   1 );
        pq . addElement ( "third" ,   50 );
        pq . addElement ( "fifth" ,   92 );
        pq . addElement ( "second" ,   10 );
        pq . addElement ( "fourth" ,   55 );

         while   ( ! pq . isEmpty ())
         {
             System . out . println ( pq . removeNext ());
         }
     }
}

Chap21/PriorityQueue/PrioritizedObject.java

Chap21/PriorityQueue/PrioritizedObject.java

/**
 * PrioritizedObject represents a node in a priority queue containing a
 * comparable object, arrival order, and a priority value.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   PrioritizedObject < T >   implements   Comparable < PrioritizedObject >
{
     private   static   int  nextOrder  =   0 ;
     private   int  priority ;
     private   int  arrivalOrder ;
     private  T element ;

     /**
     * Creates a new PrioritizedObject with the specified data.
     *
     *  @param  element the element of the new priority queue node
     *  @param  priority the priority of the new queue node
     */
     public   PrioritizedObject ( T element ,   int  priority )  
     {
         this . element  =  element ;
         this . priority  =  priority ;
        arrivalOrder  =  nextOrder ;
        nextOrder ++ ;
     }

     /**
     * Returns the element in this node.
     *
     *  @return  the element contained within the node
     */
     public  T getElement ()  
     {
         return  element ;
     }

     /**
     * Returns the priority value for this node.
     *
     *  @return  the integer priority for this node
     */
     public   int  getPriority ()  
     {
         return  priority ;
     }

     /**
     * Returns the arrival order for this node.
     *
     *  @return  the integer arrival order for this node
     */
     public   int  getArrivalOrder ()  
     {
         return  arrivalOrder ;
     }

     /**
     * Returns a string representation for this node.
     *
     */
     public   String  toString ()  
     {
         return   ( element  +   "  "   +  priority  +   "  "   +  arrivalOrder );
     }

     /**
     * Returns 1 if the this object has higher priority than 
     * the given object and -1 otherwise.
     *
     *  @param  obj the object to compare to this node
     *  @return  the result of the comparison of the given object and 
     *         this one
     */
     public   int  compareTo ( PrioritizedObject  obj )  
     {
         int  result ;

         if   ( priority  >  obj . getPriority ())
            result  =   1 ;
         else   if   ( priority  <  obj . getPriority ())
            result  =   - 1 ;
         else   if   ( arrivalOrder  >  obj . getArrivalOrder ())
            result  =   1 ;
         else
            result  =   - 1 ;

         return  result ;
     }
}


Chap21/PriorityQueue/PriorityQueue.java

Chap21/PriorityQueue/PriorityQueue.java

import  jsjf . * ;

/**
 * PriorityQueue implements a priority queue using a heap.
 * 
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   PriorityQueue < T >   extends   ArrayHeap < PrioritizedObject < T >>
{
     /**
     * Creates an empty priority queue.
     */
     public   PriorityQueue ()  
     {
         super ();
     }

     /**
     * Adds the given element to this PriorityQueue.
     *
     *  @param  object the element to be added to the priority queue
     *  @param  priority the integer priority of the element to be added
     */
     public   void  addElement ( T object ,   int  priority )  
     {
         PrioritizedObject < T >  obj  =   new   PrioritizedObject < T > ( object ,  priority );
         super . addElement ( obj );
     }

     /**
     * Removes the next highest priority element from this priority 
     * queue and returns a reference to it.
     *
     *  @return  a reference to the next highest priority element in this queue
     */
     public  T removeNext ()  
     {
         PrioritizedObject < T >  obj  =   ( PrioritizedObject < T > ) super . removeMin ();
         return  obj . getElement ();
     }
}

Chap24/Graph/jsjf/exceptions/ElementNotFoundException.java

Chap24/Graph/jsjf/exceptions/ElementNotFoundException.java

package  jsjf . exceptions ;

/**
 * ElementNotFoundException represents the situation in which a target element 
 * is not present in a collection
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   ElementNotFoundException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     */
     public   ElementNotFoundException   ( String  collection )
     {
         super   ( "The target element is not in this "   +  collection );
     }
}

Chap24/Graph/jsjf/exceptions/EmptyCollectionException.java

Chap24/Graph/jsjf/exceptions/EmptyCollectionException.java

package  jsjf . exceptions ;

/**
 * Represents the situation in which a collection is empty.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   EmptyCollectionException   extends   RuntimeException
{
     /**
     * Sets up this exception with an appropriate message.
     *  @param  collection the name of the collection
     */
     public   EmptyCollectionException   ( String  collection )
     {
         super   ( "The "   +  collection  +   " is empty." );
     }
}

Chap24/Graph/jsjf/Graph.java

Chap24/Graph/jsjf/Graph.java

package  jsjf ;

import  jsjf . exceptions . * ;
import  java . util . * ;

/**
 * Graph represents an adjacency matrix implementation of a graph.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   class   Graph < T >   implements   GraphADT < T >
{
     protected   final   int  DEFAULT_CAPACITY  =   5 ;
     protected   int  numVertices ;      // number of vertices in the graph
     protected   boolean [][]  adjMatrix ;      // adjacency matrix
     protected  T []  vertices ;      // values of vertices
     protected   int  modCount ;

     /**
     * Creates an empty graph.
     */
     public   Graph ()
     {
        numVertices  =   0 ;
         this . adjMatrix  =   new   boolean [ DEFAULT_CAPACITY ][ DEFAULT_CAPACITY ];
         this . vertices  =   ( T [])   ( new   Object [ DEFAULT_CAPACITY ]);
     }

     /**
     * Inserts an edge between two vertices of the graph.
     *
     *  @param  vertex1  the first vertex
     *  @param  vertex2  the second vertex
     */
     public   void  addEdge ( T vertex1 ,  T vertex2 )
     {
        addEdge ( getIndex ( vertex1 ),  getIndex ( vertex2 ));
     }

     /**
     * Inserts an edge between two vertices of the graph.
     *
     *  @param  index1  the first index
     *  @param  index2  the second index
     */
     public   void  addEdge ( int  index1 ,   int  index2 )
     {
         if   ( indexIsValid ( index1 )   &&  indexIsValid ( index2 ))
         {
            adjMatrix [ index1 ][ index2 ]   =   true ;
            adjMatrix [ index2 ][ index1 ]   =   true ;
            modCount ++ ;
         }
     }

     /**
     * Removes an edge between two vertices of the graph.
     *
     *  @param  vertex1  the first vertex
     *  @param  vertex2  the second vertex
     */
     public   void  removeEdge ( T vertex1 ,  T vertex2 )
     {
         // To be completed as a Programming Project
     }

     /**
     * Removes an edge between two vertices of the graph.
     *
     *  @param  index1  the first index
     *  @param  index2  the second index
     */
     public   void  removeEdge ( int  index1 ,   int  index2 )
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds a vertex to the graph, expanding the capacity of the graph
     * if necessary.
     */
     public   void  addVertex ()
     {
         // To be completed as a Programming Project
     }

     /**
     * Adds a vertex to the graph, expanding the capacity of the graph
     * if necessary.  It also associates an object with the vertex.
     *
     *  @param  vertex  the vertex to add to the graph
     */
     public   void  addVertex ( T vertex )
     {         
         if   (( numVertices  +   1 )   ==  adjMatrix . length )
            expandCapacity ();

        vertices [ numVertices ]   =  vertex ;
         for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )
         {
            adjMatrix [ numVertices ][ i ]   =   false ;
            adjMatrix [ i ][ numVertices ]   =   false ;
         }         
        numVertices ++ ;
        modCount ++ ;
     }

     /**
     * Removes a single vertex with the given value from the graph.  
     *
     *  @param  vertex  the vertex to be removed from the graph
     */
     public   void  removeVertex ( T vertex )
     {
         // To be completed as a Programming Project
     }

     /**
     * Removes a vertex at the given index from the graph.  Note that 
     * this may affect the index values of other vertices.
     *
     *  @param  index  the index at which the vertex is to be removed from
     */
     public   void  removeVertex ( int  index )
     {
         // To be completed as a Programming Project
     }

     /**
     * Returns an iterator that performs a depth first traversal 
     * starting at the given index.
     *
     *  @param  startIndex the index from which to begin the traversal
     *  @return  an iterator that performs a depth first traversal
     */
     public   Iterator < T >  iteratorDFS ( int  startIndex )
     {
         Integer  x ;
         boolean  found ;
         StackADT < Integer >  traversalStack  =   new   LinkedStack < Integer > ();
         UnorderedListADT < T >  resultList  =   new   ArrayUnorderedList < T > ();
         boolean []  visited  =   new   boolean [ numVertices ];

         if   ( ! indexIsValid ( startIndex ))
             return  resultList . iterator ();

         for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )
            visited [ i ]   =   false ;
        
        traversalStack . push ( new   Integer ( startIndex ));
        resultList . addToRear ( vertices [ startIndex ]);
        visited [ startIndex ]   =   true ;
        
         while   ( ! traversalStack . isEmpty ())
         {
            x  =  traversalStack . peek ();
            found  =   false ;

             //  Find a vertex adjacent to x that has not been visited
             //  and push it on the stack 
             for   ( int  i  =   0 ;   ( <  numVertices )   &&   ! found ;  i ++ )
             {
                 if   ( adjMatrix [ x . intValue ()][ i ]   &&   ! visited [ i ])
                 {
                    traversalStack . push ( new   Integer ( i ));
                    resultList . addToRear ( vertices [ i ]);
                    visited [ i ]   =   true ;
                    found  =   true ;
                 }
             }
             if   ( ! found  &&   ! traversalStack . isEmpty ())
                traversalStack . pop ();
         }
         return   new   GraphIterator ( resultList . iterator ());
     }

     /**
     * Returns an iterator that performs a depth first search 
     * traversal starting at the given vertex.
     *
     *  @param  startVertex the vertex to begin the search from
     *  @return  an iterator that performs a depth first traversal
     */
     public   Iterator < T >  iteratorDFS ( T startVertex )
     {         
         return  iteratorDFS ( getIndex ( startVertex ));
     }

     /**
     * Returns an iterator that performs a breadth first  
     * traversal starting at the given index.
     *
     *  @param  startIndex the index from which to begin the traversal
     *  @return  an iterator that performs a breadth first traversal
     */
     public   Iterator < T >  iteratorBFS ( int  startIndex )
     {
         Integer  x ;
         QueueADT < Integer >  traversalQueue  =   new   LinkedQueue < Integer > ();
         UnorderedListADT < T >  resultList  =   new   ArrayUnorderedList < T > ();

         if   ( ! indexIsValid ( startIndex ))
             return  resultList . iterator ();

         boolean []  visited  =   new   boolean [ numVertices ];
         for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )
            visited [ i ]   =   false ;
        
        traversalQueue . enqueue ( new   Integer ( startIndex ));
        visited [ startIndex ]   =   true ;
        
         while   ( ! traversalQueue . isEmpty ())
         {
            x  =  traversalQueue . dequeue ();
            resultList . addToRear ( vertices [ x . intValue ()]);

             //  Find all vertices adjacent to x that have not been visited
             //  and queue them up 
            
             for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )
             {
                 if   ( adjMatrix [ x . intValue ()][ i ]   &&   ! visited [ i ])
                 {
                    traversalQueue . enqueue ( new   Integer ( i ));
                    visited [ i ]   =   true ;
                 }
             }
         }
         return   new   GraphIterator ( resultList . iterator ());
     }
    
     /**
     * Returns an iterator that performs a breadth first search 
     * traversal starting at the given vertex.
     *
     *  @param  startVertex the vertex to begin the search from
     *  @return  an iterator that performs a breadth first traversal
     */
     public   Iterator < T >  iteratorBFS ( T startVertex )
     {         
         return  iteratorBFS ( getIndex ( startVertex ));
     }

     /**
     * Returns an iterator that contains the indices of the vertices 
     * that are in the shortest path between the two given vertices.
     *
     *  @param  startIndex the starting index
     *  @param  targetIndex the the target index
     *  @return  the an iterator containing the indices of the 
     *               of the vertices making the shortest path between
     *               the given indices
     */
     protected   Iterator < Integer >  iteratorShortestPathIndices
                                         ( int  startIndex ,   int  targetIndex )
     {
         int  index  =  startIndex ;
         int []  pathLength  =   new   int [ numVertices ];
         int []  predecessor  =   new   int [ numVertices ];
         QueueADT < Integer >  traversalQueue  =   new   LinkedQueue < Integer > ();
         UnorderedListADT < Integer >  resultList  =  
                                              new   ArrayUnorderedList < Integer > ();

         if   ( ! indexIsValid ( startIndex )   ||   ! indexIsValid ( targetIndex )   ||  
                                                     ( startIndex  ==  targetIndex ))
             return  resultList . iterator ();

         boolean []  visited  =   new   boolean [ numVertices ];
         for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )
            visited [ i ]   =   false ;
        
        traversalQueue . enqueue ( new   Integer ( startIndex ));
        visited [ startIndex ]   =   true ;
        pathLength [ startIndex ]   =   0 ;
        predecessor [ startIndex ]   =   - 1 ;

         while   ( ! traversalQueue . isEmpty ()   &&   ( index  !=  targetIndex ))
         {
            index  =   ( traversalQueue . dequeue ()). intValue ();

             //Update the pathLength for each unvisited vertex adjacent 
             //     to the vertex at the current index. 
             for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )
             {
                 if   ( adjMatrix [ index ][ i ]   &&   ! visited [ i ])
                 {
                    pathLength [ i ]   =  pathLength [ index ]   +   1 ;
                    predecessor [ i ]   =  index ;
                    traversalQueue . enqueue ( new   Integer ( i ));
                    visited [ i ]   =   true ;
                 }
             }
         }
         if   ( index  !=  targetIndex )    // no path must have been found
             return  resultList . iterator ();

         StackADT < Integer >  stack  =   new   LinkedStack < Integer > ();
        index  =  targetIndex ;
        stack . push ( new   Integer ( index ));
         do
         {
            index  =  predecessor [ index ];
            stack . push ( new   Integer ( index ));
         }   while   ( index  !=  startIndex );
        
         while   ( ! stack . isEmpty ())
            resultList . addToRear ((( Integer ) stack . pop ()));

         return   new   GraphIndexIterator ( resultList . iterator ());
     }

     /**
     * Returns an iterator that contains the shortest path between
     * the two vertices.
     *
     *  @param  startIndex the starting index
     *  @param  targetIndex the target index
     *  @return  an iterator that contains the shortest path
     *           between the given vertices
     */
     public   Iterator < T >  iteratorShortestPath ( int  startIndex ,  
                                                          int  targetIndex )
     {
         UnorderedListADT < T >  resultList  =   new   ArrayUnorderedList < T > ();
         if   ( ! indexIsValid ( startIndex )   ||   ! indexIsValid ( targetIndex ))
             return  resultList . iterator ();

         Iterator < Integer >  it  =  iteratorShortestPathIndices ( startIndex ,  
                                      targetIndex );         
         while   ( it . hasNext ())
            resultList . addToRear ( vertices [(( Integer ) it . next ()). intValue ()]);
         return   new   GraphIterator ( resultList . iterator ());
     }

     /**
     * Returns an iterator that contains the shortest path between
     * the two vertices.
     *
     *  @param  startVertex the starting vertex
     *  @param  targetVertex the target vertex
     *  @return  an iterator that contains the shortest path between
     *         the given vertices
     */
     public   Iterator < T >  iteratorShortestPath ( T startVertex ,  T targetVertex )
     {
         return  iteratorShortestPath ( getIndex ( startVertex ),  
                                             getIndex ( targetVertex ));
     }

     /**
     * Returns the weight of the least weight path in the network.  
     * Returns positive infinity if no path is found.
     *
     *  @param  startIndex the starting index
     *  @param  targetIndex the target index
     *  @return  the integer weight of the least weight path
     *                in the network
     */
     public   int  shortestPathLength ( int  startIndex ,   int  targetIndex )
     {
         int  result  =   0 ;
         if   ( ! indexIsValid ( startIndex )   ||   ! indexIsValid ( targetIndex ))
             return   0 ;

         int  index1 ,  index2 ;
         Iterator < Integer >  it  =  iteratorShortestPathIndices ( startIndex ,  
                                      targetIndex );

         if   ( it . hasNext ())
            index1  =   (( Integer ) it . next ()). intValue ();
         else
             return   0 ;

         while   ( it . hasNext ())
         {
            result ++ ;
            it . next ();
         }
        
         return  result ;
     }

     /**
     * Returns the weight of the least weight path in the network.  
     * Returns positive infinity if no path is found.
     *
     *  @param  startVertex the starting vertex
     *  @param  targetVertex the target vertex
     *  @return  the integer weight of the least weight path
     *            in the network
     */
     public   int  shortestPathLength ( T startVertex ,  T targetVertex )
     {
         return  shortestPathLength ( getIndex ( startVertex ),  getIndex ( targetVertex ));
     }

     /**
     * Returns a minimum spanning tree of the graph.
     *
     *  @return  a minimum spanning tree of the graph
     */
     public   Graph < T >  getMST ()
     {
         int  x ,  y ;
         int []  edge  =   new   int [ 2 ];
         StackADT < int [] >  vertexStack  =   new   LinkedStack < int [] > ();
         Graph < T >  resultGraph  =   new   Graph < T > ();

         if   ( isEmpty ()   ||   ! isConnected ())
             return  resultGraph ;
        
        resultGraph . adjMatrix  =   new   boolean [ numVertices ][ numVertices ];
        
         for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )
             for   ( int  j  =   0 ;  j  <  numVertices ;  j ++ )
                resultGraph . adjMatrix [ i ][ j ]   =   false ;
                
        resultGraph . vertices  =   ( T [])( new   Object [ numVertices ]);
         boolean []  visited  =   new   boolean [ numVertices ];
        
         for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )
            visited [ i ]   =   false ;         
        
        edge [ 0 ]   =   0 ;
        resultGraph . vertices [ 0 ]   =   this . vertices [ 0 ];
        resultGraph . numVertices ++ ;
        visited [ 0 ]   =   true ;

         // Add all edges that are adjacent to vertex 0 to the stack. 
         for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )
         {
             if   ( ! visited [ i ]   &&   this . adjMatrix [ 0 ][ i ])
             {
                edge [ 1 ]   =  i ;
                vertexStack . push ( edge . clone ());
                visited [ i ]   =   true ;
             }
         }

         while   (( resultGraph . size ()   <   this . size ())   &&   ! vertexStack . isEmpty ())
         {
             // Pop an edge off the stack and add it to the resultGraph. 
            edge  =  vertexStack . pop ();
            x  =  edge [ 0 ];
            y  =  edge [ 1 ];
            resultGraph . vertices [ y ]   =   this . vertices [ y ];
            resultGraph . numVertices ++ ;
            resultGraph . adjMatrix [ x ][ y ]   =   true ;
            resultGraph . adjMatrix [ y ][ x ]   =   true ;
            visited [ y ]   =   true ;

             // Add all unvisited edges that are adjacent to vertex y
             // to the stack. 
             for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )
             {
                 if   ( ! visited [ i ]   &&   this . adjMatrix [ i ][ y ])
                 {
                    edge [ 0 ]   =  y ;
                    edge [ 1 ]   =  i ;
                    vertexStack . push ( edge . clone ());
                    visited [ i ]   =   true ;
                 }
             }
         }

         return  resultGraph ;
     }

     /**
     * Creates new arrays to store the contents of the graph with
     * twice the capacity.
     */
     protected   void  expandCapacity ()
     {
        T []  largerVertices  =   ( T [])( new   Object [ vertices . length  *   2 ]);
         boolean [][]  largerAdjMatrix  =  
                 new   boolean [ vertices . length  *   2 ][ vertices . length  *   2 ];

         for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )
         {
             for   ( int  j  =   0 ;  j  <  numVertices ;  j ++ )
             {
                largerAdjMatrix [ i ][ j ]   =  adjMatrix [ i ][ j ];
             }
            largerVertices [ i ]   =  vertices [ i ];
         }

        vertices  =  largerVertices ;
        adjMatrix  =  largerAdjMatrix ;
     }

     /**
     * Returns the number of vertices in the graph.
     *
     *  @return  the integer number of vertices in the graph
     */
     public   int  size ()
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns true if the graph is empty and false otherwise. 
     *
     *  @return  true if the graph is empty
     */
     public   boolean  isEmpty ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns true if the graph is connected and false otherwise. 
     *
     *  @return  true if the graph is connected
     */
     public   boolean  isConnected ()
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns the index value of the first occurrence of the vertex.
     * Returns -1 if the key is not found.
     *
     *  @param  vertex the vertex whose index value is being sought
     *  @return  the index value of the given vertex
     */
     public   int  getIndex ( T vertex )
     {
         // To be completed as a Programming Project
        
         return   0 ;    // temp
     }

     /**
     * Returns true if the given index is valid. 
     *
     *  @param  index the index whose validity is being queried
     *  @return  true if the given index is valid
     */
     protected   boolean  indexIsValid ( int  index )
     {
         // To be completed as a Programming Project
        
         return   true ;    // temp
     }

     /**
     * Returns a copy of the vertices array.
     *
     *  @return  a copy of the vertices array
     */
     public   Object []  getVertices ()
     {
         // To be completed as a Programming Project
        
         return   null ;    // temp
     }
    
     /**
     * Returns a string representation of the adjacency matrix. 
     *
     *  @return   a string representation of the adjacency matrix
     */
     public   String  toString ()
     {
         if   ( numVertices  ==   0 )
             return   "Graph is empty" ;

         String  result  =   "Adjacency Matrix\n" ;
        result  +=   "----------------\n" ;
        result  +=   "index\t" ;

         for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )  
         {
            result  +=   ""   +  i ;
             if   ( <   10 )
                result  +=   " " ;
         }
        result  +=   "\n\n" ;

         for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )
         {
            result  +=   ""   +  i  +   "\t" ;
        
             for   ( int  j  =   0 ;  j  <  numVertices ;  j ++ )
             {
                 if   ( adjMatrix [ i ][ j ])
                    result  +=   "1 " ;
                 else
                    result  +=   "0 " ;
             }
            result  +=   "\n" ;
         }

        result  +=   "\n\nVertex Values" ;
        result  +=   "\n-------------\n" ;
        result  +=   "index\tvalue\n\n" ;

         for   ( int  i  =   0 ;  i  <  numVertices ;  i ++ )
         {
            result  +=   ""   +  i  +   "\t" ;
            result  +=  vertices [ i ]. toString ()   +   "\n" ;
         }
        result  +=   "\n" ;
         return  result ;
     }
    
     /**
     * Inner class to represent an iterator over the elements of this graph
     */
     protected   class   GraphIterator   implements   Iterator < T >
     {
         private   int  expectedModCount ;
         private   Iterator < T >  iter ;
        
         /**
         * Sets up this iterator using the specified iterator.
         *
         *  @param  iter the list iterator created by a graph traversal
         */
         public   GraphIterator ( Iterator < T >  iter )
         {
             this . iter  =  iter ;
            expectedModCount  =  modCount ;
         }
        
         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( ! ( modCount  ==  expectedModCount ))
                 throw   new   ConcurrentModificationException ();
            
             return   ( iter . hasNext ());
         }
        
         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return  the next element in the iteration
         *  @throws  NoSuchElementException if the iterator is empty
         */
         public  T next ()   throws   NoSuchElementException
         {
             if   ( hasNext ())
                 return   ( iter . next ());
             else  
                 throw   new   NoSuchElementException ();
         }
        
         /**
         * The remove operation is not supported.
         * 
         *  @throws  UnsupportedOperationException if the remove operation is called
         */
         public   void  remove ()
         {
             throw   new   UnsupportedOperationException ();
         }
     }
    
     /**
     * Inner class to represent an iterator over the indexes of this graph
     */
     protected   class   GraphIndexIterator   implements   Iterator < Integer >
     {
         private   int  expectedModCount ;
         private   Iterator < Integer >  iter ;
        
         /**
         * Sets up this iterator using the specified iterator.
         *
         *  @param  iter the list iterator created by a graph traversal
         */
         public   GraphIndexIterator ( Iterator < Integer >  iter )
         {
             this . iter  =  iter ;
            expectedModCount  =  modCount ;
         }
        
         /**
         * Returns true if this iterator has at least one more element
         * to deliver in the iteration.
         *
         *  @return   true if this iterator has at least one more element to deliver
         *          in the iteration
         *  @throws   ConcurrentModificationException if the collection has changed
         *          while the iterator is in use
         */
         public   boolean  hasNext ()   throws   ConcurrentModificationException
         {
             if   ( ! ( modCount  ==  expectedModCount ))
                 throw   new   ConcurrentModificationException ();
            
             return   ( iter . hasNext ());
         }
        
         /**
         * Returns the next element in the iteration. If there are no
         * more elements in this iteration, a NoSuchElementException is
         * thrown.
         *
         *  @return  the next element in the iteration
         *  @throws  NoSuchElementException if the iterator is empty
         */
         public   Integer  next ()   throws   NoSuchElementException
         {
             if   ( hasNext ())
                 return   ( iter . next ());
             else  
                 throw   new   NoSuchElementException ();
         }
        
         /**
         * The remove operation is not supported.
         * 
         *  @throws  UnsupportedOperationException if the remove operation is called
         */
         public   void  remove ()
         {
             throw   new   UnsupportedOperationException ();
         }
     }
}

Chap24/Graph/jsjf/GraphADT.java

Chap24/Graph/jsjf/GraphADT.java

package  jsjf ;

import  java . util . Iterator ;

/**
 * GraphADT defines the interface to a graph data structure.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   GraphADT < T >
{
     /** 
     * Adds a vertex to this graph, associating object with vertex. 
     * 
     *  @param  vertex the vertex to be added to this graph
     */
     public   void  addVertex ( T vertex );

     /** 
     * Removes a single vertex with the given value from this graph. 
     * 
     *  @param  vertex the vertex to be removed from this graph
     */
     public   void  removeVertex ( T vertex );

     /** 
     * Inserts an edge between two vertices of this graph. 
     *
     *  @param  vertex1 the first vertex
     *  @param  vertex2 the second vertex
     */
     public   void  addEdge ( T vertex1 ,  T vertex2 );

     /** 
     * Removes an edge between two vertices of this graph. 
     *
     *  @param  vertex1 the first vertex
     *  @param  vertex2 the second vertex
     */
     public   void  removeEdge ( T vertex1 ,  T vertex2 );

     /** 
     * Returns a breadth first iterator starting with the given vertex. 
     * 
     *  @param  startVertex the starting vertex
     *  @return  a breadth first iterator beginning at the given vertex
     */
     public   Iterator  iteratorBFS ( T startVertex );

     /** 
     * Returns a depth first iterator starting with the given vertex. 
     *
     *  @param  startVertex the starting vertex
     *  @return  a depth first iterator starting at the given vertex
     */
     public   Iterator  iteratorDFS ( T startVertex );

     /** 
     * Returns an iterator that contains the shortest path between
     * the two vertices. 
     *
     *  @param  startVertex the starting vertex
     *  @param  targetVertex the ending vertex
     *  @return  an iterator that contains the shortest path
     *         between the two vertices
     */
     public   Iterator  iteratorShortestPath ( T startVertex ,  T targetVertex );

     /** 
     * Returns true if this graph is empty, false otherwise. 
     *
     *  @return  true if this graph is empty
     */
     public   boolean  isEmpty ();

     /** 
     * Returns true if this graph is connected, false otherwise. 
     *
     *  @return  true if this graph is connected
     */
     public   boolean  isConnected ();

     /** 
     * Returns the number of vertices in this graph. 
     *
     *  @return  the integer number of vertices in this graph
     */
     public   int  size ();

     /** 
     * Returns a string representation of the adjacency matrix. 
     *
     *  @return  a string representation of the adjacency matrix
     */
     public   String  toString ();
}

Chap24/Graph/jsjf/NetworkADT.java

Chap24/Graph/jsjf/NetworkADT.java

package  jsjf ;

/**
 * NetworkADT defines the interface to a network.
 *
 *  @author  Java Foundations
 *  @version  4.0
 */
public   interface   NetworkADT < T >   extends   GraphADT < T >
{
     /** 
     * Inserts an edge between two vertices of this graph. 
     *
     *  @param  vertex1 the first vertex
     *  @param  vertex2 the second vertex
     *  @param  weight the weight 
     */
     public   void  addEdge ( T vertex1 ,  T vertex2 ,   double  weight );
    
     /** 
     * Returns the weight of the shortest path in this network. 
     *
     *  @param  vertex1 the first vertex
     *  @param  vertex2 the second vertex
     *  @return  the weight of the shortest path in this network
     */
     public   double  shortestPathWeight ( T vertex1 ,  T vertex2 );
}