Computer Science 2310
Fall 2009
Exercises for Quiz 10

This will be a closed book quiz. You may bring one 8.5x11 page of prepared notes, written on both sides.

  1. Review practice questions for quiz 9.

  2. Think of stacking up wooden blocks. First you place one block on a table, then add another block on top of it, then a third on top of the second block, etc.

    Each block has a string written on it. We will describe a block by its string. For example, if a block has "cat" written it, then we call it block "cat".

    Suppose that an object of class Stack is supposed to represent a stack of blocks inside a computer program. When you create a new stack, it has no blocks in it. A Stack object allows you to add a new block to the top of the stack, or to remove the top block from the top, or to ask which block is currently on the top of the stack, or whether the stack is empty.

    The following is a partial implementation of the Stack class. A stack holds an array where all of the blocks in the stack are put. Since a block is identified by its string, the array holds strings.

    A stack object also holds an integer telling how many blocks are currently in the stack. It is initially 0 since the stack starts out empty.

    Your job is to finish the definition of the stack class.

      class Stack
      {
        private int height;        // current number of blocks in the stack
        private String[] content;  // array holding height blocks
    
        public Stack()
        {
          height = 0;
          content = new String[100];  // Maximum of 100 blocks in the stack at once.
        }
    
        // addBlock(which) adds a block labeled by string 'which'
        // onto the top of the stack.  It presumes that there
        // is enough room for it.
    
        public void addBlock(String which)
        {
           ...
        }
    
        // removeBlock() removes the top block from the stack.
        // It presumes that there is a block to remove.
    
        public void removeBlock()
        {
           ...
        }
    
        // topBlock() returns the string that labels the top
        // block on the stack.  It presumes that there is at
        // least one block in the stack.
    
        public String topBlock()
        {
           ...
        }
    
        // isEmpty() returns true if the stack currently has
        // no blocks in it.
    
        public boolean isEmpty()
        {
          ...
        }
      }
    
  3. Write the addBlock method.

    Answer

  4. Write the removeBlock method.

    Answer

  5. Write the topBlock method.

    Answer

  6. Write the isEmpty method.

    Answer