Key to CSE143 Midterm, Fall 2012 handout #20 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. before after code -----------------------+-----------------------+------------------------------- | | | | q.next.next = p; p->[1]->[2] | p->[2] | p = p.next; | | q.next.next.next = null; | | q->[3]->[4] | q->[3]->[4]->[1] | | | | | -----------------------+-----------------------+------------------------------- | | | | p.next.next = p; p->[1]->[2] | p->[2]->[1] | p = p.next; | | p.next.next = null; | | q.next.next = q; q->[3]->[4] | q->[4]->[3] | q = q.next; | | q.next.next = null; | | -----------------------+-----------------------+------------------------------- | | | | ListNode temp = p.next.next; p->[1]->[2]->[3] | p->[1]->[4] | temp.next = p.next; | | p.next = q; | | q.next = null; q->[4] | q->[3]->[2] | q = temp; | | temp.next.next = null; | | -----------------------+-----------------------+------------------------------- 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 Nov 2 08:48:52 PDT 2012