// Program to test solutions to problem #8 on the cse143x midterm, fall 2024. // Fill in your solution to alternatingReverse, then compile and run the // program. import java.util.*; public class Test8 { 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) { Queue q = new LinkedList<>(); int oldSize = s.size(); stackToQueue(s, q); 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()); } queueToStack(q, s); } // post: Values from s moved to q (added in stack order, top to bottom); // s is empty public static void stackToQueue(Stack s, Queue q) { while (!s.isEmpty()) { int n = s.pop(); q.add(n); } } // post: Values from q moved to s (added in queue order, front to back); // q is empty public static void queueToStack(Queue q, Stack s) { while (!q.isEmpty()) { int n = q.remove(); s.push(n); } } 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(); } }