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;
- public class MirrorHalves {
- public static <T extends Number> Queue<T> mirrorHalves(Queue<T> queue) {
- Stack<T> stack = new Stack<>();
- int sizeQueue = queue.size();
- for (int k = 0; k < 2; k++) {
- for (int i = 0; i < sizeQueue / 2; i++) {
- T poll = queue.poll();
- queue.add(poll);
- stack.push(poll);
- }
- while (!stack.isEmpty()) {
- queue.add(stack.pop());
- }
- }
- return queue;
- }
- public static void main(String args[]) {
- Queue<Integer> queue = new ArrayDeque<>();
- Integer array[]= new Integer[]{10, 50, 19, 54, 30, 67};
- queue.addAll(Arrays.asList(array));
- System.out.printf("\n Original Queue: %s\n", queue);
- queue = mirrorHalves(queue);
- System.out.printf("\n Original Queue: %s\n", queue);
- }
- }
- /**
- * Write a method mirrorHalves that accepts a queue of integers as a parameter and replaces each half of that queue
- * with itself plus a mirrored version of itself (the same elements in the opposite order).
- * For example, suppose a queue variable q stores the following elements:
- * <p>
- * front [10, 50, 19, 54, 30, 67] back
- * After a call of mirrorHalves(q);, the queue would store the following elements:
- * <p>
- * front [10, 50, 19, 19, 50, 10, 54, 30, 67, 67, 30, 54] back
- * If your method is passed an empty queue, the result should be an empty queue.
- * If your method is passed a null queue or one whose size is not even, your method should throw an IllegalArgumentException.
- * <p>
- * You may use one stack or one queue (but not both) 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 code must run in O(n) time where n is the number of elements of the original queue.
- */
Advertisement
Add Comment
Please, Sign In to add comment