Saint Louis University |
CS A 220
|
Dept. of Mathematics and |
We have seen the interface Stack (Code Fragment 4.1) and the interface Queue (Code Fragment 4.8), both of which are assumed to have unlimited capacity. For this problem you are to assume that someone has already implemented the Stack interface (but due to encapsulation, you should make no assumptions about the details of that implementation)
We want you to give a Java class which implements the Queue interface, using only two Stack's as instance variables (you are free to define local variables within particular methods if you wish).
Your code should start with the lines,
public class SolutionQueue implements Queue { private Stack S1 = new AnImplementedStack(); private Stack S2 = new AnImplementedStack();
and should go on to contain code for the methods enqueue(o), dequeue(), size(), isEmpty(), and front(). To be successful, you will need to have a good understanding of both sides of "the wall" defined by an interface. You are simultaneously in the role of the implementor of a Queue, yet the user of someone else's Stack implementation.
To get you going, a natural implementation for the Queue.size() method in this setting might be:
since all elements of the queue must be stored, and S1 and S2 are your only means of storage. (of course, if you decide to store an element in both stacks for some reason, you may have to adjust this size() implementation)public int size() { // returns the size of the Queue return (S1.size() + S2.size()); }
If you understand the goal, it is now time to think about how to solve the problem. Remember, anytime dequeue() is called, your Queue must behave with a "first-in, first-out" principle. Make sure your code works for any sequence of enqueue(), dequeue(), and front() operations