Write a method called reverseByN that takes a queue of integers and an integer n as parameters and that reverses each successive sequence of length n in the queue. For example, suppose that a variable called q stores the following sequence of values:

front [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] back

and we make the following call:

reverseByN(q, 3);

Then q should store the following values after the call:

front [3, 2, 1, 6, 5, 4, 9, 8, 7, 12, 11, 10, 15, 14, 13] back

Notice that the first three values (1, 2, 3) have been reversed, as have the next three values (4, 5, 6), the next three values (7, 8, 9), and so on. If the size of the queue is not an even multiple of n, then there will be a sequence of fewer than n values at the end. This sequence should be reversed as well. For example, if q stores this sequence:

front [8, 9, 15, 27, -3, 14, 42, 8, 73, 19] back

and we make the call:

reverseByN(q, 4);

Then q should store the following values after the call:

front [27, 15, 9, 8, 8, 42, 14, -3, 19, 73] back

Notice that the two sequences of length 4 have been reversed along with the sequence of two values at the end (73, 19). If n is greater than the size of the queue, then the method should reverse the entire sequence.

You are to use one stack as auxiliary storage to solve this problem. You may not use any other auxiliary data structures to solve this problem, although you can have as many simple variables as you like. Use the Queue interfaces and the Stack and LinkedList classes discussed in lecture.

Solution

Below is one possible solution for this problem. We encourage you to try to solve it on your own before looking at this solution since it is hard to “unsee” a solution.

Solution

In class, we did not get to the part of the solution to handle queues of lengths not-divisible by n. To do this, we had to figure out how many elements are left over, and then manually repeat the code to go from queue -> stack -> queue for just those elements.

public void reverseByN(Queue<Integer> q, int n) {
    Stack<Integer> s = new Stack<>();
    int times = q.size() / n;
    int extra = q.size() % n;
    for (int i = 0; i < times; i++) {
        for (int j = 0; j < n; j++) {
            s.push(q.remove());
        }
        s2q(s, q);
    }
    for (int i = 0; i < extra; i++) {
        s.push(q.remove());
    }
    s2q(s, q);
}