Homework Q Question
Homework Q Question
Homework Q Question
Multiple Choice
3. Consider the implementation of the Queue using a circular array. What goes wrong
if we try to keep all the items at the front of a partially-filled array (so that data[0] is
always the front).
4. In the circular array version of the Queue class, which operations require linear
time for their worst-case behavior?
o A. remove
o B. insert when the capacity has not yet been reached
o C. isEmpty
o D. None of these operations require linear time.
5. Suppose remove is called on a priority queue that has exactly two entries with equal
priority. How is the return value of remove selected?
o A. One is chosen at random.
o B. The one which was inserted first.
o C. The one which was inserted most recently.
o D. This can never happen (violates the precondition)
1
For questions 6- 8, consider the following operations on a Queue data structure that stores
int values.
Queue q = new Queue( );
q.enqueue(3);
q.enqueue(5);
q.enqueue(9);
System.out.println(q.dequeue( )); // d1
q.enqueue(2);
q.enqueue(4);
System.out.println(q.dequeue( )); // d2
System.out.println(q.dequeue( )); // d3
q.enqueue(1);
q.enqueue(8);
6. After the code above executes, how many elements would remain in q?
a) 0
b) 4
c) 5
d) 6
e) 7
7. What value is returned by the last dequeue operation (denoted above with a d3 in
comments)?
a) 3
b) 5
c) 9
d) 2
e) 4
2) __Queues and Stacks can be implemented using either arrays or linked lists.
3) ___In order to input a list of values and output them in order, you could use a
Queue. In order to input a list of values and output them in opposite order, you
could use a Stack.
2
Free Form
1. A Queue q stores int values. Show what q will look like after each of the following
instructions is executed.
q.enqueue(6);
q.enqueue(12);
q.enqueue(13);
q.dequeue( );
q.dequeue( );
q.enqueue(19);
q.enqueue(21);
q.enqueue(22);
q.dequeue( );
q.enqueue(20);
private Node(int v)
{
value = v;
next = null;
}
}
public boolean isEmpty(); //check whether the queue is empty
public Node peek(); //return a node from the front
3
public Node dequeue(); //remove a node from the front
public void enqueue(Node item); //add a new node at the end
public int size(); //return the number of nodes in the queue
}
Implement Enqueue method
Suppose that q is represented by a linked list. Draw the state of the private instance
variables of q after the above code:
_______
front| |
|_______|
_______
rear | |
|_______|
5. .Describe why it is a bad idea to implement a linked list version of a queue that uses the
head of the list as the rear of the queue and no tail pointer.