Basically I've been given an implementation of a CircularQueue, I need to implement a method called 'public boolean contains (E other)' which is supposed to return true if the parameter 'other' exists in my queue.
I was ok with it because it was an array, but then I saw this other condition to it which is bugging me.
Remember that you cannot freely navigate across all elements in a queue. Only the front element is accessible at any time through the peek method. Your implementation of the contains and intersectWith methods MUST NOT make use of any extra queue to temporarily hold some of the elements of this queue.
Would an Iterator be applicable to solve this problem?
Any help is highly appreciated.
Mjall
Solution:
Answer I came up with, method rotate description: The method rotate( int n ) removes n elements from the front of the queue and adds them to the rear of the queue. The elements are added at the rear of the queue in the same order as they are removed from the front of the queue. For example, given a queue q containing the elements \A, B, C, D, E", where the element A is at the front of the queue, following the method call q.rotate( 2 ), the content of the queue will be \C, D, E, A, B";
public boolean contains(E elem) {
while( this.isEmpty() != true){
if(this.peek() == elem){return true;}
else{rotate(1);}
}
return false;
}
An iterator would not be practical for this situation.
Since it's a circular queue, you can remember the first thing you've seen (not necessarily removing it from the circular queue entirely), and dequeue/enqueue elements until you find what you're looking for, or arrive at the first dequeued node.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With