Lab 7 Practice Exercise Solutions

  1. public class StackBasedQueueOfInts {
    
       private StackOfInts stack;
    
       public StackBasedQueueOfInts() {
         stack = new StackOfInts();
       }
    
       public void enqueue(int n) {
          stack.push(n);
       }
    
       public int dequeue() {
          if (isEmpty()) throw new Error("Empty queue on dequeue");
          StackOfInts temp = new StackOfInts();
          while (!stack.isEmpty())  temp.push(stack.pop());
          int ans = temp.pop();
          while (!temp.isEmpty())  stack.push(temp.pop());
          return ans;
       }
    
       public boolean isEmpty() { return stack.isEmpty(); }
    
    }
    
    
  2. public class QueueBasedStackOfInts {
    
       private QueueOfInts queue;
    
       public QueueBasedStackOfInts() {
          queue = new QueueOfInts();
       }
    
       public void push(int n) {
          queue.enqueue(n);
       }
    
       public int pop() {
          if (isEmpty()) throw new Error("Stack underflow");
          int ans = 0;  // bogus initialization
          QueueOfInts temp = new QueueOfInts();
          while (!isEmpty()) {
             int n = queue.dequeue();
             if (isEmpty()) ans = n;
             else temp.enqueue(n);
          }
    
          while (!temp.isEmpty()) queue.enqueue(temp.dequeue());
    
          return ans;
       }
    
       public boolean isEmpty() { return queue.isEmpty(); }
    }
    
    
  3. Neither would be a real implementation: each would be abstractly based on the other.
  4. public class Square extends Rectangle {
       public Square(int length) {
          this.length = length;
          this.width  = length;
       }
    }