Important Notice:

Practice-It will be discontinued as of November 1st, 2024. After this date, the website will remain online for a transitional period, but login will be restricted to University of Washington NetID authentication. This marks the next phase towards the platform's full retirement. Thank you for your use and support of the application over the years.

If you are looking for an alternative, a similar tool, CodeStepByStep, was developed independently by the original author of Practice-It, and is available at codestepbystep.com**

logo Practice-It logo

BJP4 Exercise 14.20: interleave

Language/Type: Java Collections Stacks and Queues
Author: Marty Stepp (on 2016/09/08)

Write a method interleave that accepts a queue of integers as a parameter and rearranges the elements by alternating the elements from the first half of the queue with those from the second half of the queue. For example, suppose a variable q stores the following sequence of values:

front [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] back

If we make the call of interleave(q);, the queue should store the following values after the call:

front [1, 6, 2, 7, 3, 8, 4, 9, 5, 10] back

To understand the result, consider the two halves of this list. The first half is [1, 2, 3, 4, 5] and the second half is [6, 7, 8, 9, 10]. These are combined in an alternating fashion to form a sequence of interleave pairs: the first values from each half (1 and 6), then the second values from each half (2 and 7), then the third values from each half (3 and 8), and so on. In each pair, the value from the first half appears before the value from the second half. The previous example uses sequential integers to make the interleaving more obvious, but the same process can be applied to any sequence of even length. For example, if q had instead stored these values:

front [2, 8, -5, 19, 7, 3, 24, 42] back

Then the method would have rearranged the list to become:

front [2, 7, 8, 3, -5, 24, 19, 42] back

Your method should throw an IllegalArgumentException if the queue does not have even size. You may 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. You may not use recursion to solve this problem. For full credit, your solution must run in O(n) time, where n represents the size of the queue.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.