X1672: Mutate a queue

Description

Write a method mutateQueue(Queue<Integer> q, int k) that will mutate the queue as described below.

  • If k is zero, do nothing and just return.

  • If k is odd, then remove from the queue the number of elements indicated by the value of k. For example, if k is 3, then remove 3 elements from the queue. If k is larger than the size of the queue, then just empty the queue and return.

  • If k is even, you have to add k values to the queue. The values to be added are the counter from 1 to k squared. For example, if k is 4, then add 4 values to the queue, 1 * 1, 2 * 2, 3 * 3, and 4 * 4 (in that order).

In summary:

  • do nothing if k is 0
  • dequeue() k times if k is odd
  • enqueue(x * x) for x = 1 to k if k is even

Constraints

  • The argument q is never null, but might be empty.

Reference

For reference, a Queue is defined as shown below.

public class Queue<E> {
   public void clear();
   public boolean enqueue(E it);
   public E dequeue();
   public E peek();
   public int size();
   public boolean isEmpty();
}

Your Answer:

Feedback

Your feedback will appear here when you check your answer.