Complete the implementation of the static method int remove(Queue q, E e, int n)
ID: 3809567 • Letter: C
Question
Complete the implementation of the static method int remove(Queue q, E e, int n), which removes the first n occurrences of e in q. The method must work for any implementation of the interface Queue: public interface Queue {boolean isEmpty(); void enqueue(E e); E dequeue ();} Following a call to the method remove, the elements in the queue must remain in the same order, except that the first n occurrences of e have been removed. The method throws NullPointerException if either q or e are null. It throws IllegalArgumentException if n is a negative number. If the queue had less than n occurrences of e, the returned value represents the excess of elements that could not be removed. Consider the example below. Since you do not know the size of the queue, you cannot use an array for temporary storage. Instead, you must either use a queue or a stack (or both). You can assume the existence of the class LinkedQueue, which implements the interface Queue, as well as LinkedStack. which implements the interface Stack. public interface Stack {boolean isEmpty(); E peek (); E pop(); void push(E e); Executing the test program below produces the following output: LinkedQueue: {A, B, R, A, C, A, D, A, B, R, A) 0 LinkedQueue: {B, R, C, D, A, B, R, A} 2 LinkedQueue: {B, R, D, A, B, R, A} Queue q; q = new LinkedQueue(); q.enqueue("A"); q.enqueue("B"); q.enqueue("R"); q.enqueue("A"); q.enqueue("C"); q.enqueue("A"); q.enqueue("D"); q.enqueue("A"); q.enqueue("B"); q.enqueue("R"); q.enqueue("A"); System .out. println(q); System. out. println (remove (q, "A", 3)); System .out. println(q); System. out. println (remove(q, "C", 3)); System .out. println(q);Explanation / Answer
class RemoveFromQueueDemo
{
public static void main(String[] args)
{
Queue <String> q;
q = new LinkedQueue <String> ();
q.enqueue("A");
q.enqueue("B");
q.enqueue("R");
q.enqueue("A");
q.enqueue("C");
q.enqueue("A");
q.enqueue("D");
q.enqueue("A");
q.enqueue("B");
q.enqueue("R");
q.enqueue("A");
System.out.println(q);
System.out.println(remove(q, "A", 3));
System.out.println(q);
System.out.println(remove(q, "C", 3));
System.out.println(q);
}
public static int remove(Queue<E> q, E e, int n)
{
if(n < 0)
throw new IllegalArgumentException(n);
else if(q == null || e == null)
throw new NullPointerException();
Stack <String> s = new LinkedStack <String> ();
while(!q.isEmpty())
{
E temp = q.dequeue();
if(temp == e & n != 0)
n--;
else
s.push(temp);
}
while(!s.isEmpty())
q.enqueue(s.pop());
return n;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.