Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayDeque;
- import java.util.Arrays;
- import java.util.Queue;
- import java.util.Stack;
- import java.util.stream.IntStream;
- public class InterleaveQueue {
- public static final int I_DONT_KNOW_WHY = 3;
- public static <T extends Number> Queue<T> interleave(Queue<T> queue) {
- Stack<T> stack = new Stack<>();
- int sizeQueue = queue.size();
- int sizeStack;
- for (int j = 0; j < I_DONT_KNOW_WHY; j++) {
- /* First half goes in Stack */
- IntStream.range(0, sizeQueue / 2).forEach(i -> stack.push(queue.poll()));
- System.out.printf("Q:%-40s S:%-40s\n", queue, stack);
- /* All from Stack into Queue */
- sizeStack = stack.size();
- IntStream.range(0, sizeStack).forEach(i -> queue.add(stack.pop()));
- System.out.printf("Q:%-40s S:%-40s\n", queue, stack);
- }
- /* First half goes in Stack */
- IntStream.range(0, sizeQueue / 2).forEach(i -> stack.push(queue.poll()));
- System.out.printf("Q:%-40s S:%-40s\n", queue, stack);
- for (int i = 0; i < sizeQueue / 2; i++) {
- T poll = queue.poll();
- T pop = stack.pop();
- queue.add(poll);
- queue.add(pop);
- }
- System.out.printf("Q:%-40s S:%-40s\n", queue, stack);
- return queue;
- }
- public static void main(String args[]) {
- Integer array[] = IntStream.rangeClosed(1, 10).boxed().toArray(Integer[]::new);
- Queue<Integer> queue = new ArrayDeque<>();
- if (queue.size() % 2 != 0) throw new IllegalArgumentException();
- Arrays.stream(array).forEach(queue::add);
- System.out.printf("\n Original Queue: %s\n", queue);
- queue = interleave(queue);
- System.out.printf("\n Original Queue: %s\n", queue);
- }
- }
- /**
- * 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:
- * <p>
- * 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:
- * <p>
- * front [1, 6, 2, 7, 3, 8, 4, 9, 5, 10] back
- * <p>
- * 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.
- */
Advertisement
Add Comment
Please, Sign In to add comment