// Program to test solutions to problem #6 on the cse143 midterm, winter 2020. // Fill in your solution to alternatingReverse, then compile and run the // program. Note that it does not test whether the exception is thrown. import java.util.*; public class Test6 { public static void alternatingReverse(Stack s) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static void alternatingReverse2(Stack s) { if (s.size() % 2 != 0) { throw new IllegalArgumentException(); } Queue q = new LinkedList<>(); int oldSize = s.size(); while (!s.isEmpty()) { q.add(s.pop()); } for (int i = 0; i < oldSize / 2; i++) { s.push(q.remove()); q.add(q.remove()); } while (!s.isEmpty()) { q.add(q.remove()); q.add(s.pop()); } while (!q.isEmpty()) { s.push(q.remove()); } } private static int testCount; private static int failCount; public static void main(String[] args) { test(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}); test(new int[] {101, 103, 105, 107, 109, 111, 113, 115, 117, 119}); test(new int[] {200, 204, 208, 212, 216, 220, 224, 228, 232, 236}); test(new int[] {10, 21, 12, 23, 14, 25, 16, 27, 18, 27, 20, 29}); test(new int[] {21, 12, 23, 14, 25, 16, 27, 18, 27, 20, 29, 22}); test(new int[] {-3, 0, 13, 42, 203, 98, 4279, 42, -5, -4, 13, 42}); test(new Stack<>()); if (failCount == 0) { System.out.println("passed all tests"); } else { System.out.println("failed " + failCount + " of " + testCount + " tests"); } } public static void test(int[] data) { Stack s = new Stack<>(); for (int i = 0; i < data.length / 2; i++) { s.push(data[2 * i]); s.push(data[2 * i + 1]); test(s); } } public static void test(Stack s) { Stack s2 = new Stack<>(); for (int n : s) { s2.push(n); } System.out.println("original = " + s); alternatingReverse2(s); System.out.println("result = " + s); boolean fail = false; try { alternatingReverse(s2); } catch (RuntimeException e) { int line = e.getStackTrace()[0].getLineNumber(); System.out.println(" threw " + e + " at line #" + line); fail = true; } if (!fail && !s.equals(s2)) { System.out.println("yours = " + s2); fail = true; } testCount++; if (fail) { System.out.println("failed"); failCount++; } else { System.out.println("passed"); } System.out.println(); } }