Filip_Markoski

[ADSx] - MirrorHalves Queue

Jan 17th, 2018
399
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1. import java.util.ArrayDeque;
  2. import java.util.Arrays;
  3. import java.util.Queue;
  4. import java.util.Stack;
  5.  
  6. public class MirrorHalves {
  7.  
  8.     public static <T extends Number> Queue<T> mirrorHalves(Queue<T> queue) {
  9.         Stack<T> stack = new Stack<>();
  10.         int sizeQueue = queue.size();
  11.  
  12.         for (int k = 0; k < 2; k++) {
  13.             for (int i = 0; i < sizeQueue / 2; i++) {
  14.                 T poll = queue.poll();
  15.                 queue.add(poll);
  16.                 stack.push(poll);
  17.             }
  18.             while (!stack.isEmpty()) {
  19.                 queue.add(stack.pop());
  20.             }
  21.         }
  22.         return queue;
  23.     }
  24.  
  25.     public static void main(String args[]) {
  26.         Queue<Integer> queue = new ArrayDeque<>();
  27.  
  28.         Integer array[]= new Integer[]{10, 50, 19, 54, 30, 67};
  29.  
  30.         queue.addAll(Arrays.asList(array));
  31.  
  32.         System.out.printf("\n Original Queue: %s\n", queue);
  33.  
  34.         queue = mirrorHalves(queue);
  35.         System.out.printf("\n Original Queue: %s\n", queue);
  36.     }
  37. }
  38. /**
  39.  * Write a method mirrorHalves that accepts a queue of integers as a parameter and replaces each half of that queue
  40.  * with itself plus a mirrored version of itself (the same elements in the opposite order).
  41.  * For example, suppose a queue variable q stores the following elements:
  42.  * <p>
  43.  * front [10, 50, 19, 54, 30, 67] back
  44.  * After a call of mirrorHalves(q);, the queue would store the following elements:
  45.  * <p>
  46.  * front [10, 50, 19, 19, 50, 10, 54, 30, 67, 67, 30, 54] back
  47.  * If your method is passed an empty queue, the result should be an empty queue.
  48.  * If your method is passed a null queue or one whose size is not even, your method should throw an IllegalArgumentException.
  49.  * <p>
  50.  * You may use one stack or one queue (but not both) as auxiliary storage to solve this problem.
  51.  * You may not use any other auxiliary data structures to solve this problem, although you can have as many simple variables as you like.
  52.  * You may not use recursion to solve this problem.
  53.  * For full credit your code must run in O(n) time where n is the number of elements of the original queue.
  54.  */
Advertisement
Add Comment
Please, Sign In to add comment