Key to CSE143 Midterm, Spring 2007 handout #23 1. One possible solution appears below. public void printSum(ArrayIntList list) { ArrayIntListIterator i = list.iterator(); if (i.hasNext()) { System.out.print(i.next()); while (i.hasNext()) System.out.print(" + " + i.next()); } System.out.println(); } 2. One possible solution appears below. public void stretch(ArrayList<Integer> list) { for (int i = 0; i < list.size(); i += 2) { int n = list.get(i); list.set(i, n / 2 + n % 2); list.add(i + 1, n / 2); } } 3. Method Call Output Produced ----------------------------------------------- mystery(7); 7 mystery(38); 838 mystery(194); 49194 mystery(782); 28782 mystery(3842); 2483842 4. One possible solution appears below. public void rotate() { if (front != null && front.next != null) { ListNode temp = front; front = front.next; ListNode current = front; while (current.next != null) current = current.next; current.next = temp; temp.next = null; } } 5. Statement Output ------------------------------------------------------------ var1.method1(); Nose 1 var2.method1(); Eye 1/Mouth 1 var3.method1(); Eye 1/Mouth 1 var1.method2(); Mouth 2/Nose 1 var2.method2(); Ear 2 var3.method2(); Mouth 2/Eye 1/Mouth 1 var4.method2(); compiler error var5.method2(); Mouth 2/Nose 1 var6.method2(); Ear 2 var1.method3(); compiler error var2.method3(); Ear 3 var3.method3(); compiler error ((Nose)var5).method3(); Nose 3 ((Eye)var1).method1(); Nose 1 ((Eye)var4).method1(); runtime error ((Nose)var1).method3(); Nose 3 ((Mouth)var4).method1(); Mouth 1 ((Ear)var5).method3(); runtime error ((Eye)var6).method3(); compiler error ((Mouth)var4).method2(); Mouth 2/Mouth 1 6. One possible solution appears below. public void reorder(Queue<Integer> q) { Stack<Integer> s = new ArrayStack<Integer>(); int oldSize = q.size(); for (int i = 0; i < oldSize; i++) { int n = q.dequeue(); if (n < 0) s.push(n); else q.enqueue(n); } int newSize = q.size(); while (!s.isEmpty()) q.enqueue(s.pop()); for (int i = 0; i < newSize; i++) q.enqueue(q.dequeue()); } 7. 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 *= 2; }
Stuart Reges
Last modified: Fri Sep 16 16:16:07 PDT 2011