Key to CSE143 Midterm, Spring 2012 handout #23 1. Method Call Output Produced ------------------------------------------------ mystery(1); 1 mystery(2); 2, 1 mystery(4); 4, 2, 1 mystery(8); 8, 4, 2, 1 mystery(10); 10, 5, 16, 8, 4, 2, 1 2. One possible solution appears below. public void printDashed(int n) { if (n < 0) { System.out.print("-"); printDashed(-n); } else if (n < 10) { System.out.print(n); } else { printDashed(n / 10); System.out.print("-" + n % 10); } } 3. One possible solution appears below. public int removeLast() { if (front == null) { throw new NoSuchElementException(); } else if (front.next == null) { int result = front.data; front = null; return result; } else { ListNode current = front; while (current.next.next != null) { current = current.next; } int result = current.next.data; current.next = null; return result; } } 4. Statement Output ------------------------------------------------------------ var1.method1(); Peak 1/Cliff 3/Peak 3 var2.method1(); Peak 1/Gorge 3 var3.method1(); Peak 1/Hill 3 var4.method1(); Peak 1/Gorge 3 var5.method1(); Peak 1/Peak 3 var6.method1(); compiler error var1.method2(); compiler error var2.method2(); Gorge 2 var3.method2(); compiler error var1.method3(); Cliff 3/Peak 3 var2.method3(); Gorge 3 var3.method3(); Hill 3 ((Gorge)var6).method1(); runtime error ((Cliff)var3).method2(); compiler error ((Gorge)var4).method2(); Gorge 2 ((Gorge)var3).method2(); runtime error ((Hill)var3).method2(); Hill 2 ((Gorge)var1).method1(); runtime error ((Cliff)var4).method3(); Gorge 3 ((Peak)var6).method3(); Cliff 3/Peak 3 5. One possible solution appears below. public int removeMin(Stack<Integer> s) { Queue<Integer> q = new LinkedList<Integer>(); int min = s.pop(); q.add(min); while (!s.isEmpty()) { int next = s.pop(); if (next < min) min = next; q.add(next); } while (!q.isEmpty()) { int next = q.remove(); if (next != min) s.push(next); } while (!s.isEmpty()) q.add(s.pop()); while (!q.isEmpty()) s.push(q.remove()); return min; } 6. One possible solution appears below. public void mirror() { int last = 2 * size - 1; for (int i = 0; i < size; i++) { elementData[last - i] = elementData[i]; } size = size * 2; }
Stuart Reges
Last modified: Fri Sep 16 16:16:07 PDT 2011