Java Reference
In-Depth Information
front = myQueue.getFront(); // returns "Jess"
System.out.println(front + " is at the front of the queue.");
front = myQueue.dequeue(); // removes and returns "Jess"
System.out.println(front + " is removed from the queue.");
Parts a through e of Figure 10-2 illustrate the five additions to the queue. Following these addi-
tions, the queue contains—from front to back—the strings Jim , Jess , Jill , Jane , and Joe . The string
at the front of the queue is Jim ; getFront retrieves it. The method dequeue retrieves Jim again and
then removes it from the queue (Figure 10-2f). A subsequent call to enqueue adds Jerry to the back
of the queue but does not affect the front (Figure 10-2g). Thus, getFront retrieves Jess , and
dequeue retrieves Jess and then removes it (Figure 10-2h).
If we now were to execute dequeue repeatedly until the queue was empty, an additional call to
either dequeue or getFront would return null .
FIGURE 10-2
A queue of strings after (a) enqueue adds Jim ; (b) enqueue adds
Jess ; (c) enqueue adds Jill ; (d) enqueue adds Jane ; (e) enqueue
adds Joe ; (f) dequeue retrieves and removes Jim ; (g) enqueue
adds Jerry ; (h) dequeue retrieves and removes Jess
Jim
(a)
Jim
Jess
(b)
Jess
Jill
Jim
(c)
Jim
Jess
Jill
Jane
(d)
Jim
Jess
Jill
Jane
Joe
(e)
Jess
Jill
Jane
Joe
(f)
Jess
Jill
Jane
Joe
Jerry
(g)
Jill
Jane
Joe
Jerry
(h)
Question 1 After the following nine statements execute, what string is at the front of the
queue and what string is at the back?
QueueInterface<String> myQueue = new LinkedQueue<String>();
myQueue.enqueue("Jim");
myQueue.enqueue("Jess");
myQueue.enqueue("Jill");
myQueue.enqueue("Jane");
String name = myQueue.dequeue();
myQueue.enqueue(name);
myQueue.enqueue(myQueue.getFront());
name = myQueue.dequeue();
 
Search WWH ::




Custom Search