Key to CSE143 Midterm, Winter 2005 handout #21 1. Method Call Value Returned ------------------------------------------ mystery(1, 3) 9 mystery(4, 4) 7 mystery(3, 5) 21 mystery(1, 5) 25 mystery(4, 7) 40 2. One possible solution appears below. public static void countToBy(int n, int m) { if (m <= 0 || n <= 0) throw new IllegalArgumentException(); else if (n <= m) System.out.print(n); else { countToBy(n - m, m); System.out.print(", " + n); } } 3. One possible solution appears below. public int lastIndexOf(int n) { int result = -1; int index = 0; ListNode current = this.front; while (current != null) { if (current.data == n) { result = index; } index++; current = current.next; } return result; } 4. Statement Output ------------------------------------------------------------ var1.method2(); Ocean 2 var2.method2(); Pond 2 var3.method2(); Pond 2 var4.method2(); compiler error var5.method2(); Bay 2 var6.method2(); Ocean 2 var1.method3(); Lake 3/Ocean 2 var2.method3(); compiler error var3.method3(); compiler error var4.method3(); compiler error var5.method3(); Lake 3/Bay 2 var6.method3(); Lake 3/Ocean 2 ((Ocean)var5).method1(); runtime error ((Lake)var3).method3(); Lake 3/Pond 2 ((Lake)var4).method1(); compiler error ((Ocean)var1).method1(); Bay 1/Pond 2 ((Bay)var4).method1(); Bay 1/Pond 2 ((Lake)var2).method3(); runtime error ((Ocean)var5).method1(); runtime error ((Pond)var4).method2(); Bay 2 5. Two possible solutions appear below. public boolean isPalindrome(Queue<Integer> q) { Stack<Integer> s = new ArrayStack<Integer>(); for (int i = 0; i < q.size(); i++) { int n = q.dequeue(); q.enqueue(n); s.push(n); } boolean ok = true; for (int i = 0; i < q.size(); i++) { int n1 = q.dequeue(); int n2 = s.pop(); if (n1 != n2) ok = false; q.enqueue(n1); } return ok; } public static boolean isPalindrome(Queue<Integer> q) { Stack<Integer> s = new ArrayStack<Integer>(); int oldSize = q.size(); for (int i = 0; i < oldSize / 2; i++) { int n = q.dequeue(); s.push(n); } int oddValue = 0; if (oldSize % 2 == 1) oddValue = q.dequeue(); boolean ok = true; while (!s.isEmpty()) { int n1 = q.dequeue(); int n2 = s.pop(); if (n1 != n2) ok = false; q.enqueue(n1); q.enqueue(n2); } for (int i = 0; i < oldSize / 2; i++) { int n1 = q.dequeue(); int n2 = q.dequeue(); q.enqueue(n1); s.push(n2); } while (!s.isEmpty()) q.enqueue(s.pop()); if (oldSize % 2 == 1) q.enqueue(oddValue); for (int i = 0; i < oldSize / 2; i++) q.enqueue(q.dequeue()); return ok; } 6. One possible solution appears below. public boolean isPairwiseSorted() { for (int i = 0; i < size - 1; i += 2) if (elementData[i] > elementData[i + 1]) return false; return true; }
Stuart Reges
Last modified: Fri Feb 17 11:21:57 PST 2006