// Program to test solutions to problem #5 on the cse143 midterm, fall 2011. // Fill in your solution to isConsecutive, then compile and run the program. import java.util.*; public class Test5 { public static boolean isConsecutive(Stack s) { // fill in your solution here // you can also rename the parameter above } // this is the sample solution public static boolean isConsecutive2(Stack s) { if (s.size() <= 1) return true; else { Queue q = new LinkedList(); int prev = s.pop(); q.add(prev); boolean ok = true; while (!s.isEmpty()) { int next = s.pop(); if (prev - next != 1) ok = false; q.add(next); prev = next; } while (!q.isEmpty()) s.push(q.remove()); while (!s.isEmpty()) q.add(s.pop()); while (!q.isEmpty()) s.push(q.remove()); return ok; } } public static void main(String[] args) { test(new int[] {1, 2, 3, 4, 6, 7, 8, 10}); test(new int[] {3, 2, 1}); } public static void test(int[] data) { Stack s = new Stack(); for (int n : data) { s.push(n); } test(s); while (!s.isEmpty()) { s.pop(); test(s); } System.out.println(); } public static void test(Stack s) { System.out.println("stack = " + s); boolean test1 = isConsecutive2(s); System.out.println("isConsecutive = " + test1); boolean fail = false; try { Stack s2 = new Stack(); for (int n : s) s2.push(n); boolean test2 = isConsecutive(s2); if (test1 != test2) { fail = true; System.out.println("yours = " + test2); } else if (!s.equals(s2)) { fail = true; System.out.println("yours left stack = " + s2); } } catch (RuntimeException e) { System.out.println(" threw " + e); fail = true; } if (fail) System.out.println("failed"); else System.out.println("passed"); } }