Self-Review Questions

  1. A Queue is best characterized as
    a)   Last In First Out
    b)   First In Last Out
    c)   First In First Out
    d)   None of the above

     

  2. Given an empty queue Q, what does it look like after the following operations?
    Q.enqueue(5)
    Q.enqueue(2)
    Q.dequeue()
    Q.enqueue(3)
    Q.dequeue()
    
    a)   3
    b)   5
    c)   9
    d)   none of the above

     

  3. Given a 5 element stack S (from top to bottom: 2, 4, 6, 8, 10), and an empty queue Q, remove the elements one-by-one from S and insert them into Q, then remove them one-by-one from Q and re-insert them into S. S now looks like (from top to bottom).
    a)   2, 4, 6, 8, 10
    b)   10, 2, 4, 6, 8
    c)   10, 8, 6, 4, 2
    d)   none of the above

     

  4. What is the reason for using a "circular queue" instead of a regular one?
    a)   the running time of enqueue() is improved
    b)   reuse empty spaces
    c)   you can traverse all the elements more efficiently
    d)   None of the above

     

  5. Given an efficient circular array-based queue Q capable of holding 10 objects. Show the final contents of the array after the following code is executed:
    for (int k = 1; k ≤ 7; k++)
       Q.enqueue(k);
    for (int k = 1; k ≤ 7; k++)
       Q.enqueue(Q.dequeue());
    

    Final answer:

      0     1     2     3     4     5     6     7     8     9  
      4     5     6     7           1     2     3  

     

  6. Write a method
    public Queue<String> contains(Queue<String> q, String str)
    

    that takes a Queue and an element and returns true if the Queue contains this element or false if not. The elements in the Queue must remain in their original order once this method is complete.

    public Queue contains(Queue q, String str){
    
    	Queue temp = new Queue();
    	boolean found = false;
    
    	while(!q.isEmpty()){
    		String curr = q.dequeue();
    		if(curr.equals(str)){
    			found = true;
    		}
    		temp.enqueue(curr);
    	}
    	while(!temp.isEmpty()){
    		q.enqueue(temp.dequeue());
    	}	
    	return found;
    }
    
  7. Show how to implement a queue using two stacks. What is the worst-case runtime complexity of the dequeue method?

    To implement a queue using two stacks, consider one stack to be "input" and one stack to be "output". At any given point, all your elements are either in one stack or the other. When you are enqueuing elements, just push them onto the input stack. When you are dequeuing elements, pop all the elements from the input stack and push them onto the output stack. Then pop the top element from the output stack to get the dequeued element. The worst-case runtime complexity of dequeue is O(n).