logo Practice-It logo


Language/Type: Java Collections Stacks and Queues
Author: Stuart Reges (on 2014/02/13)

Write a method interleave that takes a queue of integers as a parameter and that rearranges the elements by interleaving the first half of the list with the second half of the list. For example, suppose a variable called q stores the following sequence of values:

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

and we make the following call:


Consider the two halves of this list:

        first half:  [1, 2, 3, 4, 5]    second half: [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. Thus, after the call, the queue stores the following values:

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

This 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 length. 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. Your solution must run in O(n) time. Use the Stack and Queue interfaces and the ArrayStack and LinkedQueue implementations discussed in lecture.

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.